コンテンツにスキップ

mod_rewriteによるHTTPからHTTPSへのリダイレクト設定

ポート80のVirtualHostで、HTTPリクエストを正式なホスト名と同じURIのHTTPS URLへ301リダイレクトする。


項目 値
OS Debian 13.x
サイト名 www.example.com
HTTP VirtualHost *:80
HTTPS VirtualHost *:443
設定ファイル /etc/apache2/sites-available/www.example.com.conf

HTTPSサイトの設定が完了し、https://www.example.com/へ直接アクセスできることを確認しておく。


1. rewriteモジュールを有効化する

Section titled “1. rewriteモジュールを有効化する”
Terminal window
sudo a2enmod rewrite

有効になったことを確認する。

Terminal window
sudo apache2ctl -M | grep rewrite

期待する表示はrewrite_moduleである。


2. HTTP用VirtualHostをリダイレクト専用にする

Section titled “2. HTTP用VirtualHostをリダイレクト専用にする”

/etc/apache2/sites-available/www.example.com.confの<VirtualHost *:80>を次のように変更する。HTTPS用の<VirtualHost *:443>はそのまま残す。

/etc/apache2/sites-available/www.example.com.conf
<VirtualHost *:80>
ServerName www.example.com
RewriteEngine On
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]
ErrorLog ${APACHE_LOG_DIR}/www.example.com-error.log
CustomLog ${APACHE_LOG_DIR}/www.example.com-access.log combined
</VirtualHost>

HTTP用VirtualHostはファイルを返さず、すべてのリクエストへ301を返す。コンテンツ配信や認証はHTTPS用VirtualHostで処理する。

このルールは、転送先のホスト名をwww.example.comに固定し、リクエストされたパスとクエリ文字列をHTTPS側へ引き継いで301を返す。クライアントが送信したHostヘッダーは転送先に使用しない。RewriteEngine、Pattern、サーバー変数、RとL、クエリ文字列の扱いはmod_rewriteによるHTTPからHTTPSへのリダイレクトを参照する。


Terminal window
sudo apache2ctl configtest
sudo systemctl reload apache2

configtestがSyntax OKになることを確認する。


HTTPへアクセスする。

Terminal window
curl -I http://www.example.com/

期待する結果は301 Moved PermanentlyとHTTPSのLocationヘッダーである。

HTTP/1.1 301 Moved Permanently
Location: https://www.example.com/

パスとクエリ文字列が維持されることを確認する。

Terminal window
curl -I 'http://www.example.com/private/?page=1'
HTTP/1.1 301 Moved Permanently
Location: https://www.example.com/private/?page=1

ポート番号を含むHostヘッダーを送っても、転送先へそのポート番号が引き継がれないことを確認する。

Terminal window
curl -I -H 'Host: www.example.com:80' http://www.example.com/

Locationはhttps://www.example.com/になる。

リダイレクト先まで追跡する場合は、任意で-Lを使う。

Terminal window
curl -IL 'http://www.example.com/private/?page=1'

/private/にPAM認証またはLDAP認証を設定している場合、最初にHTTP側の301が返り、その後HTTPS側で401のBasic認証challengeが返る。


Terminal window
sudo tail -f /var/log/apache2/www.example.com-access.log
sudo tail -f /var/log/apache2/www.example.com-error.log

アクセスログのステータスが301になり、リクエストされたパスが記録されることを確認する。

書き換え処理の詳細が必要な場合は、任意でHTTP用VirtualHostへ一時的に次を追加する。

LogLevel warn rewrite:trace2

確認後は通常のログレベルへ戻す。



  • mod_rewrite RewriteEngine、RewriteRule、サーバー変数、クエリ文字列の動作。

  • RewriteRule Flags R、Lなどのフラグ。