Q: Force HTTPS too many redirect with .htaccess, how to resolve? I know this has been asked and answered several times and I have gone through a lot of them but still have not solved my issue.
I have the following code in my .htaccess file.
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

I want to redirect all of the following:


*

*http://www.example.com

*http://example.com

*https://example.com
to redirect to https://www.example.com.
Currently it comes up to an error page stating too many redirects, I have tried clearing cookies to no avail.
What am I doing wrong and how can I make it work?

A: Try the following:
RewriteEngine On
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)
RewriteRule ^ https://www.%1%{REQUEST_URI} [R,L]

This canonicalises both the HTTPS and www subdomain in a single rewrite. Basically, this says... For all requests that are not HTTPS OR where the hostname does not start www then redirect to https://www.example.com/<whatever>.
The %1 backreference holds the hostname, less the optional www subdomain, from the preceding CondPattern that is always matched.
You need to use the server variable HTTPS (ie. %{HTTPS}), not the environment variable HTTPS (ie. %{ENV:HTTPS}).
