LoginSignup
49
36

More than 5 years have passed since last update.

httpsへ強制リダイレクトするコピペ用RewriteRule(ELBやCloudFront対応)

Last updated at Posted at 2016-01-21
.htaccess
# force https
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteCond %{HTTP:CloudFront-Forwarded-Proto} !=https
RewriteCond %{HTTP_HOST} !=unsecure.example.com
RewriteRule ^/?(.*) https://%{HTTP_HOST}/$1 [R=301,L]
  • mod_ssl 判定は %{HTTPS} で行う。
  • ELBなど一般的なリバースプロキシで https してるときは X-Forwarded-Proto ヘッダを見る。
  • CloudFrontの場合は CloudFront-Forwarded-Proto ヘッダを通す設定をしたうえでそれを見る。
  • https リダイレクトしたくないホスト名がある場合は Host ヘッダを見て除外。
  • RewriteRule はパスマッチの頭に ^/? を付けておくと httpd.conf 直書きでも .htaccess でも使えるようになるのでコピペが捗る。

あと、個人的にはあまり使わないが Host ヘッダを通さずに X-Forwarded-for の方を採用したい場合は Host ヘッダの代わりにそっち使うようにスべし。その場合 X-Forwarded-Forは複数経由して増える場合があるのでその考慮を忘れないこと。(コピペメモは省略、後で追記するかも)

RewriteCond が多い時のTips

RewriteCond の第1引数って只の文字列なうえに複数変数とか列挙出来るので例えば上記のケースは以下のようにまとめることが出来る。

RewriteCond %{HTTPS},%{HTTP:X-Forwarded-Proto},%{HTTP:CloudFront-Forwarded-Proto} !(on|https)
RewriteCond %{HTTP_HOST} !=unsecure.example.com
RewriteRule ^/?(.*) https://%{HTTP_HOST}/$1 [R=301,L]

個人的に縦に長い条件って読みにくいので結構捗る。

49
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
36