Redirect to non-www to www version using the .htaccess file, for both secure and non-secure websites

It’s a Google best practice to only have a single version of your site available to the public and to their index. Every default hosting setup these days allows for a www, a non-www version of your site and if you have a secure, then another two versions on the https:// protocol.

Non-secure (just http://) websites

Use the following code for a non-secure, http:// only site

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

Secure (https://) websites

Use the following code for a non-secure, http:// only site

#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} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Leave a Reply

Your email address will not be published. Required fields are marked *