You should use a 301 Redirect to indicate the preferred domainname, in order to avoid problems with how the Google-Bot indexes your website and make sure no internal Duplicate Content arises due to canonicalization issues.
- Please also see: My website can be reached with and without the www. Is this harmful?
Setting up a 301 redirect to the www. host of a domain
If you have already selected the preferred domain name in the Google Search Console, as advised by Google, then you can also use a 301 redirect to send the user to the desired domain name.
In this example, we will redirect all requests from http://domain.com/ to http://www.domain.com/.
Add the following source code to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.domain.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
Result: Any request for a page on domain.com will be redirected to www.domain.com, using the HTTP statuscode 301. This also works for direct URLs, which would direct http://domain.com/file.html to http://www.domain.com/file.html.
Tip: Have a uniform internal link strategy
Once you have chosen a preferred domain name, you should decide on a uniform internal link strategy and stick to it. If, for example, you decided on using www.domain.com as your preferred domain, then you should link all internal pages according to the following pattern: http://www.domain.com/a-directory/file.html. It is also advisable to use absolute paths instead of relative ones.