AWS ELB + Nginx/Apache/IIS で httpをHTTPSにリダイレクト
AWS CloudfrontでHTTPをHTTPSにリダイレクトしていたが、一部のコンテンツが表示されなかったりと、影響が大きかった。
ただSSL化はしたかったので、AWS ELBでSSL化を行うことにした。
CloudFrontではHTTPSにリダイレクトするのは超簡単だったのだが、ELBにはその機能がない。
その代わりELBにはX-FORWARDED-PROTOがサポートされているため、X-FORWARDED-PROTOにHTTPSがなければ、301でHTTPSにリダイレクトさせる
目次
Nginx
server {
listen 80;
#....
#ここを追加
if ($http_x_forwarded_proto != https) {
return 301 https://$host$request_uri;
}
}
もしくは
server {
listen 80;
#....
location / {
#ここを追加
if ($http_x_forwarded_proto != 'https') {
return 301 https://$server_name$request_uri;
}
#....
}
}
Apache
<VirtualHost *:80>
#...
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [NE]
#...
</VirtualHost>
IIS
<rewrite xdt:Transform="Insert">
<rules>
<rule name="HTTPS rewrite behind ELB rule" stopProcessing="true">
<match url="^(.*)$" ignoreCase="false" />
<conditions>
<add input="{HTTP_X_FORWARDED_PROTO}" pattern="^http$" ignoreCase="false" />
</conditions>
<action type="Redirect" redirectType="Found" url="https://{SERVER_NAME}{URL}" />
</rule>
</rules>
</rewrite>
ヘルスチェック用設定
ELBのヘルスチェックが80番の場合は以下のようにヘルスチェック用ページだけリダイレクトしないようにする必要がある
server {
listen 80 default_server;
server_name "";
location /health {
access_log off;
return 200;
}
}
server {
listen 80;
server_name app.yourdomain.com;
#....
location / {
if ($http_x_forwarded_proto != 'https') {
return 301 https://$server_name$request_uri;
}
try_files $uri $uri/ /index.php?$args;
}
#....
}