KOMPX.COM or COMPMISCELLANEA.COM   

HTTP to HTTPS redirect in .htaccess

Redirecting from HTTP to HTTPS, when the web server serving pages is behind a load balancer or reverse proxy.

Server configuration:

That is, everything is up and running. So it is just the HTTP to HTTPS redirection that is left to get ready and start up. Directives for .htaccess file:


RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTP:X_FORWARDED_PROTO} !https [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Commentary

Enable runtime rewriting engine:


RewriteEngine On

If domain name has no www:


RewriteCond %{HTTP_HOST} !^www\. [NC]

Then replace it with domain with www:


RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

If HTTPS is not present:


RewriteCond %{HTTP:X_FORWARDED_PROTO} !https [NC]

Then replace domain without HTTPS with domain with HTTPS:


RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Notes

1. X_FORWARDED_PROTO may instead be called X-Forwarded-Proto or even else. The point is to obtain the information from a load balancer or reverse proxy on the original request it gets. Load balancers or reverse proxies may provide the web server with this info and a header named X_FORWARDED_PROTO or X-Forwarded-Proto or else may be sent, holding the protocol string. It is most often so, but not always. So it should probably be determined by practice how to get the protocol string in a particular case.

2. The other way is just to set the environment variable (if it is suitable for the given web server):


SetEnvIf X_FORWARDED_PROTO https HTTPS=on

Then directives for .htaccess file are to be like this:


RewriteEngine On
SetEnvIf X_FORWARDED_PROTO https HTTPS=on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTP:HTTPS} !on [NV]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

3. Apache Module mod_rewrite docs: http://httpd.apache.org/docs/current/mod/mod_rewrite.html

Web servers
More