This is absolutely the best implementation I have ever used: and best of all, this superb solution works well for both proxied and unproxied servers.

So, if you happen to be using any of the following services, such as.. CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing, any sort of redirect loops with normal HTTPS redirects, try the following implementation instead.

Redirect to https and www

The following .htaccess method redirects requests to the https and www canonical of your web pages and this code belongs in your sites root directory on your apache powered server.

# Canonical https - to - https://www.

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteRule (.*) https://www.%1/$1 [R=301,L]

This code does the following:

1: It checks if mod_rewrite is available

2: It checks if HTTPS is off, or if there is www

3: If either condition matches, the request is redirected

When placed in the root .htaccess, this method covers all requests, providing complete canonicalization for your domain. No further codeing is required with this code; you can just copy & paste at will.

Want to Redirect to https to the non-www version?

To redirect https and www, use the following code:

# Canonical HTTPS - to - NO www. Version

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*)$1 [L,R=301]

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# I hope this helps someone ,)