カテゴリー: BackEnd

ALB+EC2な環境でhttpをhttpsにリダイレクトする

はじめに

httpsに対応済みのWebサイトの場合、httpでアクセスされた時にhttpsでリダイレクトすることがあるとお思います。
今回は、ALB+EC2な環境でhttpでアクセスされた場合にhttpsでリダイレクトする方法を紹介します。

前提条件

Nginx 1.12.1

ALBの設定

ALBではhttpsとhttpの両方のリスナーを設定します(どちらもALB→EC2間はhttpで通信します)

リスナーの設定は下記の通りです。

 

ヘルスチェックの設定は下記の通りです。

 

Nginxの設定

下記はEC2上でRailsアプリケーションを動作させる場合のnginx.confの例です。

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user ec2-user;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    gzip                on;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;
    upstream unicorn {
        server unix:/tmp/unicorn.sock;
    }

    server {
        listen 80;
        listen [::]:80;

        server_name example.com;
        root  /home/ec2-user/www/rails-app/current/public;

        proxy_buffers 64 16k;
        proxy_max_temp_file_size 1024m;
        proxy_temp_path /dev/shm/nginx_proxy_temp;

        proxy_connect_timeout 5s;
        proxy_send_timeout 10s;
        proxy_read_timeout 10s;

        # ヘルスチェック
        location = /healthcheck.html {
            empty_gif;
            access_log off;
            break;
        }

        location ~ ^/assets/ {
            root /home/ec2-user/www/rails-app/shared/public;
        }

        location /robots.txt {
            alias /home/ec2-user/www/rails-app/current/public/robots.txt;
            break;
        }

        location / {
            if ($http_x_forwarded_proto != https) {
                rewrite ^ https://$host$request_uri permanent;
                break;
            }
            try_files $uri @app;
        }

        location @app {
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-Host  $host;
            proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;

            proxy_pass http://unix:/home/ec2-user/www/rails-app/shared/tmp/sockets/unicorn.sock;
        }
    }
}

httpでアクセスされた場合にhttpsにrewriteしているのは70〜76行目です。

$http_x_forwarded_protoを使うとクライアントがロードバランサーへの接続に使用したプロトコルを識別できます。
$http_x_forwarded_protoがhttpsではなかった時にhttpsでリダイレクトします。

注意点

注意点はリダイレクトの設定をserverディレクティブに書くのではなく、locationディレクティブに書く点です。

serverディレクティブに書いてしまうとヘルスチェックのための/healthcheck.htmlもリダイレクトしてしまうためヘルスチェックに失敗するようになってしまいます。

さいごに

先日AWS上に環境構築を行いましたが、Linuxやミドルウェアに関する知識不足を再認識しました。aws

サービスの開発を行いつつ、これらの知識を深めていこうと思います。

Hiroki Ono

シェア
執筆者:
Hiroki Ono
タグ: AWS

最近の投稿

フロントエンドで動画デコレーション&レンダリング

はじめに 今回は、以下のように…

3週間 前

Goのクエリビルダー goqu を使ってみる

はじめに 最近携わっているとあ…

4週間 前

【Xcode15】プライバシーマニフェスト対応に備えて

はじめに こんにちは、suzu…

2か月 前

FSMを使った状態管理をGoで実装する

はじめに 一般的なアプリケーシ…

3か月 前