It’s common to see domains working on WWW and non-WWW versions and is indicated as duplicate page or in other form by most website monitoring tools. It does bring in SEO issues and more.
The root cause for the problem is with server configuration, in Apache once a domain is configured server accepts and serves content for both WWW and non-WWW versions out of the box, it’s well and good as it serves your users hitting either version.
Nginx doesn’t do the same, it treats both as separate version which all servers do but it doesn’t serve both same, if configuration exist for WWW version Nginx will only server the contents if user requests WWW version. So it indeed Important to have a redirect in Nginx.
Apache this can be achieved by adding a few rules to .htacces but Nginx needs a little extra edits in Configuration.
First lets get started by creating a configuration file for both WWW and non WWW version of the domain in
/etc/nginx/sites-available/, it should have the following files ( exampe.com = yourdomain ) :
Install the site rules on the file of which the version you like to have. On the other Install the 301 permanent redirect redirect rules, Redirect rules for WWW to non-WWW is :
WWW to non-WWW
return 301 $scheme://example.com$request_uri;
non-WWW to WWW
return 301 $scheme://www.example.com$request_uri;
Once configurations are done, link the file to an entry with file name in
/etc/nginx/sites-enabled/ directory and restart the nginx in-oder for the configurations to take effect.
Server Setting for All domains
To install this rule on all sites hosted you can have the rules set on the global configuration file, with a rule to select domain too.
Redirect non-www to WWW
server_name "~^(?!www.).*" ;
return 301 $scheme://www.$host$request_uri;
In both case we are creating a new domain configuration and initiate the redirect, this is handy in one view as it prevents the site from existing on both versions but not good in other.