hamayuzinの日記

エンジニアとかデータサイエンティストとかやってます。あの時 あれやってたな的な備忘録にできれば。

【SSL/Rails】ALBorELB + Nginx + Rails の時に、httpをhttpsにredirectさせるには

ALBorELB + Nginx + Rails 環境で、http で来たのを、httpsにredirectさせたい

2つ方法があるのだが、どちらがいいのやら・・・

※通信に関しては、下記の場合です。

User -https-> ALB -http-> nginx -http> rails

ちなみに下記がポイントとなるみたい

HTTP ヘッダーおよび Classic Load Balancer - Elastic Load Balancing

rails側で設定する

rails側とかいいつつ nginxの設定がいる

server {
  listen 80;
  server_name hoge.com;

  location / {
    proxy_set_header X-Real-IP $remote_addr;

    proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://hogehoge;
  }
}

application controllerに

  force_ssl if: :use_ssl?
  def use_ssl?
    Rails.env.production?
  end

nginxで設定する場合

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;
    }
}