htaccess redirect to https://www htaccess redirect to https://www apache apache

htaccess redirect to https://www


To first force HTTPS, you must check the correct environment variable %{HTTPS} off, but your rule above then prepends the www. Since you have a second rule to enforce www., don't use it in the first rule.

RewriteEngine OnRewriteCond %{HTTPS} off# First rewrite to HTTPS:# Don't put www. here. If it is already there it will be included, if not# the subsequent rule will catch it.RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]# Now, rewrite any request to the wrong domain to use www.# [NC] is a case-insensitive matchRewriteCond %{HTTP_HOST} !^www\. [NC]RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

About proxying

When behind some forms of proxying, whereby the client is connecting via HTTPS to a proxy, load balancer, Passenger application, etc., the %{HTTPS} variable may never be on and cause a rewrite loop. This is because your application is actually receiving plain HTTP traffic even though the client and the proxy/load balancer are using HTTPS. In these cases, check the X-Forwarded-Proto header instead of the %{HTTPS} variable. This answer shows the appropriate process


Michals answer worked for me, albeit with one small modification:

Problem:

when you have a single site security certificate, a browser that tries to access your page without https:// www. (or whichever domain your certificate covers) will display an ugly red warning screen before it even gets to receive the redirect to the safe and correct https page.

Solution

First use the redirect to the www (or whichever domain is covered by your certificate) and only then do the https redirect. This will ensure that your users are not confronted with any error because your browser sees a certificate that doesn't cover the current url.

#First rewrite any request to the wrong domain to use the correct one (here www.)RewriteCond %{HTTP_HOST} !^www\.RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]#Now, rewrite to HTTPS:RewriteCond %{HTTPS} offRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


If you are using CloudFlare or a similar CDN you will get an infinite loop error with the %{HTTPS} solutions provided here. If you're a CloudFlare user you'll need to use this:

RewriteEngine OnRewriteCond %{HTTP:X-Forwarded-Proto} =httpRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]