Why Redirect From non-www To www, Or www To non-www ?

htaccess-www-to-non-www

In SEO, there are several benefits to redirect from non-www to www, or vice versa:

1. Better user experience, all pages URL are consistent, easy for users or blogger to share the link.
2. Avoid duplicate content or search result. Technically www is a subdomain, Google index both www and non-www domain differently.
3. Easy for data analysis, instead of generating two sets of data in webmaster Google webmaster tool, Google will consolidate it to become one data.
4. Split backlink popularity or page rank.
5. Easy to fix broken link redirection

Google recommended site owner to set preferred domain, but there is no additional SEO advantage of choosing one over another.

google-webmaster-set-preferred-domain

How to redirect the links?
For Linux server, users can insert the following code to .htaccess file:

Redirect non-www to www

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

Redirect www to non-www

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