2
0

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.

AWSのELB配下で動作する場合のみhttpsへリダイレクトさせる方法

Posted at

PHPのフレームワークや関連するライブラリでhttp→httpsのリダイレクトを実現しようとしたら、AWSのELB+EC2の構成ではhttpの判定がうまくできなくてハマった。

アプリケーション内でコードを書くしかないと思ったら、.htaccessの設定だけで回避できたので共有までに。

条件

  • Apache2.4で公開するWEBアプリケーション。
  • 開発環境はローカルで構築し、httpでアクセスする。
  • 本番環境はAWSのEC2上に構築し、ELB経由でアクセスする。
  • AWSのELB配下で動作するELB→EC2の通信はhttp。
  • 本番環境はhttpsでアクセスとし、httpの場合はhttpsの同じURLへリダイレクトさせたい。

解決方法

.htaccessで以下の設定をすることで解決した。

.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

RewriteCond %{HTTP:X-Forwarded-Proto} !=httpsとしてしまうと、ローカル環境で値が入っていなくてもリダイレクトされてしまうため、=httpで判定すると希望通りの動きをしてくれた。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?