見出し画像

【IT】.htaccessでのリダイレクト設定の注意点(複数RewriteRuleの使用)

皆さま
こんにちは

今日は、
複数RewriteRuleの使用時の
.htaccessでのリダイレクト設定の注意点となります。
※Apache等のWebサーバで「.htaccess」は、Webサーバの動作をディレクトリ単位で制御するためのファイルです。ファイルのリダレクとや制御等様々なことができます。

今回の内容

1.事前準備
2.意図しない挙動となる記号
3.意図しない挙動となる記述
4.修正した記述

1.事前準備

httpd.confの/var/www/htmlディレクティブの
AllowOverrideをNoneからAllへ変更します。
次にWebサーバのサービスを再起動して設定を反映します。

# Further relax access to the default document root:
<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    ##AllowOverride None
    AllowOverride All    →ここを修正

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

2.意図しない挙動となる記号

RewriteRule ^test/dt01.html$ https://www.example.com/test/#dt01 [R=301,L]
と「#」をURLに入れた時に%23と変換され意図しない挙動となりました。

また
RewriteRule ^test/dt01.html$ https://www.example.com/test/#dt01 [R=301,L,NE]とすると単体のRewriteRuleであれば動作することまでは確認できました。
※解決方法があると思いますが、今回は「#」はパスすることします。

3.意図しない挙動となる記述

以下のURLへアクセスした場合は、元々ホスト名のページを表示
https://元々ホスト名/mypage01/
https://元々ホスト名/mypage02/

以下のURLへアクセスした場合は、リダイレクト
https://リダイレクト先/weather
https://リダイレクト先/travel
https://リダイレクト先/

となるはずですが、どのURLにアクセスしてもリダイレクト先
されてしまい意図しない動作となります。

/var/www/html/.htaccessの内容

RewriteCond %{REQUEST_URI} !(^/mypage01/)
RewriteCond %{REQUEST_URI} !(^/mypage02/)

RewriteRule ^weather/ https://weather.example.com/weather/ [R=301,L]
RewriteRule ^travel/ https://travel.example.com/ [R=301,L]
RewriteRule ^(.*)$ https://www.example.com/ [R=301,L]


4.修正した記述

修正した/var/www/html/.htaccessの内容となります。
RewriteRuleを複数記載する場合は、その都度、RewriteCond(除外URL)を記載する必要がありました。

RewriteCond %{REQUEST_URI} !(^/mypage01/)
RewriteCond %{REQUEST_URI} !(^/mypage02/)
RewriteRule ^weather/ https://weather.example.com/weather/ [R=301,L]

RewriteCond %{REQUEST_URI} !(^/mypage01/)
RewriteCond %{REQUEST_URI} !(^/mypage02/)
RewriteRule ^travel/ https://travel.example.com/ [R=301,L]

RewriteCond %{REQUEST_URI} !(^/mypage01/)
RewriteCond %{REQUEST_URI} !(^/mypage02/)
RewriteRule ^(.*)$ https://www.example.com/ [R=301,L]


では

この記事が気に入ったらサポートをしてみませんか?