Monday, February 4, 2013

Elastic Load Balancer and Nginx - How to force HTTP to HTTPS


Amazon's Elastic Load Balancer supports HTTPS termination. Sometimes, you may want to rewrite all HTTP requests to HTTPS requests. Elastic Load Balancer supports a HTTP header called X_FORWARDED_PROTO. It the request going through the Elastic Load Balancer is HTTPS, the value of X_FORWARDED_PROTO will be HTTPS.

In your Nginx site conf file, check if X_FORWARDED_PROTO is HTTPS. If it is not, rewrite it to use HTTPS.

upstream domain.com {
        ip_hash;
        server 10.194.206.112:9002 max_fails=1 fail_timeout=10s;
        server 10.212.44.16:9002 max_fails=1 fail_timeout=10s;
}

server {
        listen 80;
        server_name domain.com;
        access_log /vol/logs/nginx/web_portal.access.log;

        location / {

                if ($http_x_forwarded_proto != 'https') {
                        rewrite ^ https://$host$request_uri? permanent;
                }

                proxy_pass      http://domain.com;
                proxy_next_upstream error timeout invalid_header http_500;
                proxy_connect_timeout 1;
                proxy_set_header        Host            $host;
                proxy_set_header        X-Real-IP       $remote_addr;
                proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_intercept_errors on;
                error_page 502 503 504 =200 http://www.domain.com/error.html;
        }
}

No comments:

Post a Comment