In order to perform the 301 redirect, you must add a new Nginx server block that points to your original server block.
Open your Nginx server block configuration in an editor. We'll add another configuration file in the Nginx include directory, /etc/nginx/conf.d called redirect.conf:
sudo vi /etc/nginx/conf.d/redirect.conf
Your original server block should already be defined. Depending on which direction you want to redirect, use one of the following options.
Option 1: Redirect www to non-www
If you want redirect users from www to a plain, non-www domain, insert this configuration:
New Server Block — www to non-www
server {
listen 80;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
Save and exit. This configures Nginx to redirect requests to "www.example.com" to "example.com". Note that there should be another server block that defines your non-www web server.
To put the changes into effect, restart Nginx:
sudo systemctl restart nginx
Note that if you are using HTTPS, the listen directive should be set to port 443 instead of 80.
Use this curl command to ensure that the non-www domain redirects to the www domain (replace the highlighted part with your actual domain):
curl -I http://www.example.com
You should get a 301 Moved Permanently response, that shows the non-www redirect location, like this:
Output:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 04 May 2015 18:20:19 GMT
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: http://example.com/
Of course, you should access your domain in a web browser (www and non-www) to be sure.
Option 2: Redirect non-www to www
If you want redirect users from a plain, non-www domain to a www domain, add this server block:
New Server Block — non-www to www
server {
listen 80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}
Save and exit. This configures Nginx to redirect requests to "example.com" to "www.example.com". Note that there should be another server block that defines your www web server.
To put the changes into effect, restart Nginx:
sudo systemctl restart nginx
Note that if you are using HTTPS, the listen directive should be set to port 443 instead of 80.
Use this curl command to ensure that the non-www domain redirects to the www domain (replace the highlighted part with your actual domain):
curl -I http://example.com
You should get a 301 Moved Permanently response, that shows the www redirect location, like this:
Output:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 04 May 2015 18:20:19 GMT
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: http://www.example.com/
Of course, you should access your domain in a web browser (www and non-www) to be sure.
Ref: https://www.digitalocean.com/community/tutorials/how-to-redirect-www-to-non-www-with-nginx-on-centos-7