Redirecting www traffic to non www with ubuntu and nginx

Redirecting www traffic to non www with ubuntu and nginx

Find your nginx config file and open it with your favorite editor(VIM for sure).

$vim /etc/nginx/sites-enabled/nameofyourdomain

then add the following snippet before the existing server block.

server { server_name www.yourdomain.com; return 301 $scheme://yourdomain.com$request_uri; }

Then restart nginx

$ sudo /etc/init.d/nginx restart`

You can test if it's working right

$ curl -I http://www.yourdomain.com`

You should now get a 301 Moved Permanently response that shows the non-www redirect location, like this:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.14.0 (Ubuntu)
Date: Thu, 13 Feb 2020 17:01:43 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: http://yourdomain.com/