Redirecting HTTP requests to HTTPS I have read a lot and spent a lot of hours trying to reach the right way to set a good htaccess in order to redirect an HTTP site to HTTPS.

There are a lot of tutorials on the Internet, even on Stack Overflow, but some of them seem to be outdated and don't meet good SEO practices.

The scenario is the following one:


My site has Cloudflare enabled
My site has a valid SSL on server-side


The current htaccess of my site:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^MYSITE\.cl$
RewriteRule ^(.*) http://www.MYSITE.cl/$1 [R=301]
RewriteRule ^/?find$ find.php [L]
RewriteRule ^/?do$   do.php   [L]
ErrorDocument 404 /404.html
Options -Indexes


and I want to change .htaccess in order to keep my good SEO rank on Google, use the HTTPS and keep the .WWW:

#OLD PART
RewriteEngine On
RewriteBase /

# Non-www to www (NEW PART)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [R=301,L]

# Non-SSL to SSL (NEW PART)
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

#OLD PART AGAIN
RewriteRule ^/?find$ find.php [L]
RewriteRule ^/?do$   do.php   [L]
ErrorDocument 404 /404.html
Options -Indexes


Will this work like a charm? Do you have a better idea? Does my code have any redundancy? I think that I must set Cloudflare SSL parameters to FULL SSL (STRICT). Is that right?
Since your actual machines are being handled by the Cloudflare based forwarding, you can let them handle the enforced SSL and www-prefixing rules instead.

However, if you do plan on the FULL SSL feature of cloudflare, you can combine the 2 separate rules into a single one:

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


Notice that I do not rely on the $1 part of the URI, as matching (and capturing) that is just redundant.



Similarly, the next 2 rules can be combined:

RewriteRule ^/?(do|find)$ /$1.php [L]


You can chose to leave it as $1.php, but I prefer giving paths from the doc-root in my rules. It is just a personal preference.



Lastly, consider providing some gap between the Options directive and the directives provided by mod-rewrite. Again, it is another personal habit of mine; but makes it clearer to maintain large rule sets later on.