Redirecting requests from a non-preferred domain is important because search engines consider URLs with and without “www” as two different websites.
It creates a duplicate entry, which is not suitable for SEO.
Add the following code into .htaccess file
To make the 301 redirect from www to non-www you have to add the following code into your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} www.yourwebsitehere.com
RewriteRule (.*) http://yourwebsitehere.com/$1 [R=301,L]
Or if you want to make 301 redirect from non-www to www domain add this following code:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]