Force HTTPS w/ Load Balancer and without (.htaccess rewrite)

.htaccess

I have the following code as a rewrite rule.

RewriteEngine On 
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

This seems to work great with and without a ssl terminated load balancer. My question:

are the 2 rewrite conditions "ORed" and Anded". If I remove RewriteCond %{HTTPS} off I get an infinite redirect when accessing the web server directly. (I need this to work while DNS propagates)

I am just confused by the rule

Best Answer

The rewritecond's should be or:ed as only one of the conditions will normally be true at any one time. This however would need additional syntax in the form of the OR directive: Can reduce the rewriteRule to one rule from multiple RewriteConds for 301 in htaccess?

The first rewritecond checks to see if the protocol used by the connection is not https. If this resolves as true, a redirect to https is sent to the client.

The second rewritecond checks to see if ssl has already been terminated (for example in the load balancer), at which an x-forwarded-proto http header would have been injected with the value of https. If the header value isn't https, a redirect to https is sent to the client.

Removing the first condition whilst connecting directly to the server will result in a redirection loop.

Removing the second condition whilst connecting through the load-balancer(or whichever external node does the termination) will also result in a redirection loop.

I would try(untested as I'm on an iphone):

RewriteEngine On 
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
Related Topic