Sometimes when setting up a website, always remember to do a 301 redirect for your entire website, redirecting non-www to www url or vice versa, as this help in SEO by making it search engine friendly. Doing so will help you to get rid of duplicate contents as you dont want both nonwww and www to be indexed and detected as duplicate by search engines.
If you are using Apache, you can use htaccess to redirect as below
non-www to www redirect rules (Apache)
RewriteEngine on
RewriteCond %{http_host} ^domainname.com [nc]
RewriteRule ^(.*)$ http://www.domainname.com/$1 [L,R=301]
www to non-www redirect rules (Apache)
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.domainname.com$
RewriteRule ^/?$ "http://domainname.com/" [R=301,L]
Using Cpanel? You can follow this guide to automatically create a permanent 301 redirect in .htaccess using Cpanel. Browse under Domains > Redirects section in your Cpanel
For nginx web server, use the following in your nginx virtual host to redirect to www.
Redirect non-www to www for nginx
server {
server_name domainname.com;
return 301 $scheme://www.domainname.com$request_uri;
}
Redirect www to non-www for nginx
server {
server_name www.domainname.com;
return 301 $scheme://domainname.com$request_uri;
}
Restart your nginx using service nginx restart or nprestart
Always use either one that you like to example http://demosite.com or http://www.demosite.com to shown in search results. To safely ensure it shows the desired url after setting the 301 redirect, you can access to google webmaster tool to save preferred url site.
You can use the following online redirect checker tool to check if your url redirect work – http://www.howto301redirect.com/301-redirect-checker/