99
115

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mod_rewriteでHTTP / HTTPSの切り替え

Last updated at Posted at 2014-11-28

問い合わせフォームと管理画面だけ強制的に https でアクセスさせたい場合のメモ。
いろいろと調べて試行錯誤した結果、.htaccessに以下のように書いて実現した。

/.htaccess
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  # HTTPでアクセスされた場合、
  RewriteCond %{HTTPS} off
  # 以下のURLは常に https にリダイレクトする
  RewriteCond %{HTTP_HOST} www.example.com
  RewriteCond %{REQUEST_URI} ^/admin/.*$ [OR]
  RewriteCond %{REQUEST_URI} ^/inquiry/.*$ 
  # ただし以下は除く
  RewriteCond %{REQUEST_URI} !^/assets/.*$
  RewriteCond %{REQUEST_URI} !^.*\.(js|css|gif|jpg|png|ico)$
  # https にリダイレクト
  RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

  # HTTPSでアクセスされた場合、
  RewriteCond %{HTTPS} on
  # 以下のURL以外は常に http にリダイレクトする
  RewriteCond %{HTTP_HOST} www.example.com
  RewriteCond %{REQUEST_URI} !^/admin/.*$
  RewriteCond %{REQUEST_URI} !^/inquiry/.*$
  # ただし以下は除く
  RewriteCond %{REQUEST_URI} !^/assets/.*$
  RewriteCond %{REQUEST_URI} !^.*\.(js|css|gif|jpg|png|ico)$
  # http にリダイレクト
  RewriteRule ^.*$ http://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</IfModule>
  • %{HTTP_HOST}でホストを限定してるのは、開発環境で無効化するため
  • cssや画像ファイルをリダイレクトしてしまうと https ON のページで暗号化されてないコンテンツを読み込んでしまうので除外
99
115
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
99
115

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?