Redirect www to no-www and VS

Written on 18/05/2020

Redirect www to no-www and VS

A recurring question among website owners is whether to choose non-www or www URLs. Which one to choose for my domain.

There are absolutely no SEO benefits of choosing one over another. Even Google has said that it all depends on your preference. What’s important is that you stay consistent with the one that you chose at the time of starting your website. To stay consistent you need to redirect the undesired format to the desired format

WWW URL Pros

  • WWW URL lets to set cookies for your specific www subdomain.

WWW URL Cons

  • such WWW prefix makes the URL much longer that is not preferred by Google – the shorter URLs, the better.

Non-WWW URL Cons

  • it is easier for the users to type
  • it makes the domain name for 4 characters shorter

Non-WWW URL Pros

  • non-WWW domain has no option to restrict cookies just to the root domain.
  • non-www domains don’t have CNAME records, so you can’t redirect traffic from one server to another.

Here are the rules to redirect a www URL to no-www to htaccess file:


#########################
# redirect www to no-www
######################### 
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,NE,L]
  

Here are the rules to redirect a no-www URL to www:


#########################
# redirect no-www to www
######################### 
RewriteCond %{HTTP_HOST} ^(?!www\.)(.+) [NC]
RewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]
  

Note that I used NE flag to prevent apache from escaping the query string. Without this flag, apache will change the requested URL http://www.example.com/?foo%20bar to http://www.example.com/?foo%2250bar