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

Learn more about the How to redirect to or away from www and http(s) Adobe Muse widget

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.

Table of contents

  1. Block 1 — protocols
    1. redirect-to-http
    2. redirect-to-https
  2. Block 2 — www
    1. Redirect to http and www
    2. Redirect to https and www
    3. Redirect to http and non-www
    4. Redirect to https and non-www
  3. Putting it all together
    1. http and www
    2. https and www
    3. http and non-www
    4. https and non-www
  4. Discussion

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

RewriteEngine on

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

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

https and www

RewriteEngine on

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

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

http and non-www

RewriteEngine on

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

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

https and non-www

RewriteEngine on

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

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

Discussion