LoginSignup
129
109

More than 5 years have passed since last update.

AWSのELBとNginxでhttpアクセスをhttpsにリダイレクトしたい

Posted at

はじめに

ELB上でSSL証明書の設定をしている状態で、http(80)で来たアクセスをhttps(443)に転送したい話しです。

困った事

httpsでサービスを展開したいので、httpアクセスはhttpsにリダイレクトしようと思って、こちらを参考にNginxのconfにreturn 301 https://$host$request_uri;を書いてみました。

しかし、ELBで443を80に転送される設定がある状態でこれを書くと、当たり前の話しですがリダイレクトループが発生します。

状況として
①80で待ってるNginxにアクセスが来る
returnの設定に従ってhttps(443)に転送 (つまりELBに戻る)
③また①に戻る
これが繰り返されます

やった事

ELBでリダイレクトされるとX-Forwarded-Protoというヘッダーを持ってNginxに到達します。

X-Forwarded-Proto: https

詳細はこちら↓
Elastic Load Balancing の X-Forwarded ヘッダーの詳細

これを使ってhttpかhttpsか?を判断して、httpの時だけリダイレクトするようにしました。

server {
    listen       *:80;
    server_name  aaa.com;
    root   /var/www/;
    index  index.php index.html;

    # ここの部分で判定!!
    if ($http_x_forwarded_proto != https) {
      return 301 https://$host$request_uri;
    }
}
129
109
2

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
129
109