IISでのWeb.config リダイレクト設定いろいろ 2018.11.13 TUE

IISでのWeb.config リダイレクト設定いろいろ
目次

ちょっと今日体調悪いしで帰りますー

(...苦手な話ですもんね...)

はじめに

301リダイレクト、wwwの統一、HTTPSへの強制リダイレクトなど。
IISのリダイレクトはWeb.configを編集することで可能です。
Web.configはルート上にあります。

rewriteの機能を使用するには下記のモジュールのインストールが必要です。
サーバーに前もって入れておきましょう。

URL Rewrite https://www.iis.net/downloads/microsoft/url-rewrite

方法

Web.configに下記のようにコードを追加します。

ファイルの場合 httpRedirect

httpRedirectを使用する方法です。
Permanentは301リダイレクトとなります。
リニューアルや引っ越しによって、ページ名が変わる際はこちらが一般的です。 URL変更時の301リダイレクトはGoogleも推奨しています。 https://support.google.com/webmasters/answer/93633?hl=ja

<configuration>
	<location path="example.htm">
		<system.webServer>
			<httpRedirect enabled="true" destination="https://machdesign.net" httpResponseStatus="Permanent" />
		</system.webServer>
	</location>
</configuration>

パラメーターがある場合 rewriteルール

下記は「example/?param=数字」の場合の例
ここで「appendQueryString」をfalseに指定しないと、クエリも引き継ぐので注意。
/example/100?param=100のようになってしまいます。

<!--<system.webServer>内に記述する。-->
<rewrite>
	<rules>
		<rule name="Redirect from example">
			<match url="^example/" />
			<conditions>
				<add input="{QUERY_STRING}" pattern="param=([0-9]+)" />
			</conditions>
			<action type="Redirect" url="example/{C:1}" appendQueryString="false" />
		</rule>
	</rules>
</rewrite>

www 統一 rewriteルール

wwwに統一する場合です。

www 統一...あーあれやなー

ドメインにwwwがあるかないかで、ない場合でアクセスした際にwwwがつくURLに転送するんです

<!--<system.webServer>内に記述する。-->
<rewrite>
	<rules>
		<rule name="Redirect to www" stopProcessing="true">
			<match url="(.*)" />
			<conditions trackAllCaptures="false">
				<add input="{HTTP_HOST}" matchType="Pattern" pattern="^machdesign.net$" ignoreCase="true" negate="false" />
			</conditions>
			<action type="Redirect" url="https://www.machdesign.net/{R:1}" />
		</rule>
	</rules>
</rewrite>

HTTPS強制リダイレクト rewriteルール

サイトをフルSSLにした際は、これを設定してHTTPSに強制的にリダイレクトしましょう。

HTTPS強制リダイレクトぉ...こっちはあーあれやなー

これもhttpでアクセスした場合に転送します

<!--<system.webServer>内に記述する。-->
<rewrite>
	<rules>
		<rule name="Redirect to https" enabled="true">
			<match url="(.*)" ignoreCase="true" />
			<conditions>
				<add input="{HTTPS}" pattern="off" />
			</conditions>
			<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
		</rule>
	</rules>
</rewrite>

exampleやmachdesign.netの箇所を任意のファイル、URLに置き換えてください。