Force HTTPS with AWS Elastic load balancer

amazon-elbamazon-web-servicesapache-2.2httphttps

I need to redirect all incoming HTTP traffic to HTTPS on my elastic load balancer.

I tired using Apache mod_rewrite:

 RewriteEngine On
 RewriteCond %{HTTP:X-Forwarded-Proto} !https
 RewriteRule !/status https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

Taking advantage of the X-Forwarded-Proto header added by the load balancer, this rule should instruct the users browser to request the HTTPS version of the same URL.

So far It doesn't work (no redirection happens).

What am I doing wrong?

Is there a better way to do this?

EDIT:

This eventually worked:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]

Best Answer

So I assume you have the ELB set to accept traffic on both HTTP/80 and HTTPS/443, but port-forward all to HTTP.

If you want to use your method (which is clever), are you sure what you get isn't %{X-Forwarded-Proto} -- the HTTP: prefix looks odd to me. Other than that, this looks right to me.

If this is in a virtual host or the main server config and it's still not working, you can add

RewriteLog rewrite-log
RewriteLogLevel 3

then look in the file rewrite-log to see what's actually going on. This file can be incredibly verbose, start with lower levels. Logging cannot be initiated from .htaccess files.

(I would suggest you make the flags on the RewriteRule [R=301,L] which will cause the server to send back a 301 response, which tells search engines to consider the redirect permanent, and update its links accordingly.)