ELB 経由の HTTP トラフィックを HTTPS にリダイレクトする
AWS上でELBを設定したEC2インスタンスにて、http 接続してきたユーザーを https にリダイレクトする方法をご紹介します。
通常は、ウェブサーバー内の設定で http で接続したとき、https にリダイレクトすれば問題は解決します。ただ ELB 経由の EC2 インスタンスへのアクセスは、ユーザーが http 接続しても https 接続をしても EC2 に到達した時点では http 通信になります。通常の設定を行うと無限ループに陥ります。
〇図解
ユーザー -(https接続)→ ELB -(http接続)→ EC2
ユーザー -(http接続)→ ELB -(http接続)→ EC2
ということで、nginx + ELB 環境にて http 接続を https にリダイレクトする設定を確認していきます。
nginx にて https にリダイレクトする設定
nginx にて HTTPS でリダイレクトするために、AWS では変数「$http_x_forwarded_proto」を提供しています。ユーザーが ELB に HTTP で接続してきたとき、$http_x_forwarded_proto に http と設定されているので、これを元に https へのリダイレクトを行います。
1 2 3 4 5 |
location / { if ($http_x_forwarded_proto = http) { return 301 https://$host$request_uri; } } |
〇AWS 公式「ELB の Classic Load Balancer で HTTP トラフィックを HTTPS にリダイレクトする方法を教えてください。」
https://aws.amazon.com/jp/premiumsupport/knowledge-center/redirect-http-https-elb/
実際に nginx を設定した conf ファイルの設定サンプル
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
server { listen 80; server_name example.com; root /home/example/htdocs/; index index.php index.html index.htm; location / { if ($http_x_forwarded_proto = http) { return 301 https://$host$request_uri; } try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } |

Author:しき 投稿一覧
関連する記事
インフラカテゴリの最新記事
-
- 2023.08.20
- docker,
[docker]対処法:コンテナにログインした時にvi(vim)コマンドが使えない
-
- 2023.08.20
- docker,
[docker]対処法:OCI runtime create failed exec: “bash”: executable file not found
-
- 2023.01.06
- ubuntu,
Debian/Ubuntu系統のサーバOSではcrontabのMAILFROMは使えない件について
-
- 2022.07.19
- ubuntu,
[AWS]Ubuntu22.04 LTS にSSH接続(ログイン)できない問題の解決方法
-
- 2022.06.07
[python]torch がインストールできない場合の対応策
-
- 2022.06.02
- cloudwatch,
[AWS]CloudWatchで監視を行う項目