Apache への全てのリクエストを 1 つの URL へリダイレクトする




Apache への全てのリクエストを 1 つの URL へリダイレクトする方法は次の通り。

CentOS:2.6.18-8.el5
Apache:2.2.3
を使用しました。

今回、やりたいことは http や https に関わらず、全てのリクエストに対して、
http://www.test.example/error.html へリダイレクトして、
レスポンスを返すこと。

まずは http によるリクエストをリダイレクトするために
/etc/httpd/conf/httpd.conf へ次の記述を追記する。

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.test.example(.*)
RewriteRule ^(.*)?$ http://www.test.example/error.html
</IfModule>

DocumentRoot の下辺りに追記します。

VirtualHost を利用している場合は
各 <VirtualHost></VirtualHost> の間にも上記を追記する。

さらに、https も利用している場合は、
/etc/httpd/conf.d/ssl.conf へ次の記述を追記する。

<VirtualHost></VirtualHost> の間に追記する。

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.test.example(.*)
RewriteRule ^(.*)?$ http://www.test.example/error.html
</IfModule>

設定の反映は httpd の再起動。

これでブラウザでどんなアクセスをしても
http://www.test.example/error.html にリダイレクトされる。

リダイレクトの前の URL は実在する必要はない。

リダイレクトを確認した URL は以下の通りで、
全て意図した通りにリダイレクトされました。

http://www.test.example
http://www.test.example/
https://www.test.example/
http://www.test.example/test.html
https://www.test.example/test.html
http://www.test.example/test1/test2/test3/test.html
https://www.test.example/test1/test2/test3/test.html