Force HTTPS with AWS ELB

Background

I need to redirect all incoming HTTP traffic to HTTPS on my elastic load balancer. The web servers are running via Apache.

Constraint

I don’t have SSL cert for the web servers, so traffic from HTTPS port 443 of the load balancer will be redirected to HTTP port 80 of the web servers.

Solution

  1. Create a .htaccess file in each web servers which will utilise Apache mod_rewrite
  2. We can’t simply check rewrite rule RewriteCond %{HTTPS} !=on as this will create infinite redirect since the web servers only accept HTTP traffic. But instead, we can check a HTTP header called X-FORWARDED-PROTO which will have value “HTTPS” whenever request come to the load balancer via HTTPS
  3. Last, we have to add another rule to make sure it doesn’t broke the health check. We can add exception for the health check by checking another specific HTTP header called X-Forwarded-For

The final .htaccess file will look like this

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP:X-Forwarded-For} !=""
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI}

Reference:

http://www.emind.co/how-to/how-to-force-https-behind-aws-elb

http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/x-forwarded-headers.html#x-forwarded-for

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s