.htaccess [permanent] redirect http to https + clean URLs

Here's a quick solution that has worked for me on every single one of my projects:

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ /$1 [R=301,L]

Explanation

First four lines deal with the redirect itself:

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

In this case, as the world wide standard has it, I'm defaulting all of my domains to the full version: https://www.domain.com.

I see some odd ones who strip it all down to just https://domain.com, and I used to be one of them...

The remaining 6 lines of code deal with the whole 'Clean URL' thing:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ /$1 [R=301,L]

Here you're essentially telling it to strip away all of your URL endings (domain.com/contact.html vs domain.com/contact) – permanently.

Your extension might differ from the one in this example (.html). All you would need to do is simply replace .html with .php, or .shtml, or whatever else you might have. Be sure you update all 4 lines of code.


I'd love to hear your feedback in the comments!

Share this page