How to redirect to or away from www and http(s)

John R Perry
December 28, 2016

In SEO, canonicalizing your URLs is very important. One of the first steps in this process is making sure all of your pages include (or exclude) www in your domain. This quick post will show you how to easily do this.

Add this to the beginning of your .htaccess file (it might already be there).

RewriteEngine on

Once RewriteEngine on is added, add two of the following blocks of code directly below it. If you have any 301 redirects, place them after whichever block you choose. None of the text below is a placeholder — in other words, don't change anything about the text. Any text that follows after the number sign (#) is a comment, and can be removed.

Block 1 — protocols

For the first block, we need to specify whether we want our domain to be accessed via http or https.

Redirect to http

RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{SERVER_NAME}/$1 [R=301,L]

Redirect to https

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R=301,L]

Block 2 — www

We've got everything redirecting to a single protocol, now we'll specify whether we want our domain to use www.

Redirect to http and www

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

Redirect to https and www

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

Redirect to http and non-www

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

Redirect to https and non-www

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

Putting it all together

http and www

https and www

http and non-www

https and non-www

John R Perry
December 28, 2016