Force HTTPS with mod_rewrite, including proxied SSL
I've got a server getting some traffic from an SSL terminating load balancer- in which case it comes in as HTTP over port 80 with a http_x_forwarded_proto
= "https"
I want a mod_rewrite rule that only allows direct HTTPS traffic or forwarded HTTPS traffic.
I have this so far:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:http_x_forwarded_proto} != https
RewriteCond %{HTTP:http_x_forwarded_proto} != HTTPS
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
but I'm getting
RewriteCond: bad flag delimiters
error.
What do I need to correct to get this working, and is this the best approach?
The problem was the whitespace after the "!=":
Working version:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
tricky...
If you have load balancer always use SSL when communicating with the server, you need to omit the first check as it will always be true. (If you are offloading SSL at the load balancer, the first line is always true unless someone manages to directly hit your server using SSL in which case it would be false and not try to redirect since X-Forwarded-Proto
would be missing.)
The code I'm using since we're always communicating over SSL between the ELB and the webserver:
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]