Sometimes you may need to redirect www to non-www URL to remove www from domain URL. This is useful in SEO as it helps tell search engines to treat www and non-www URLs on your website as one, and avoids any penalty. In this article we will look at how to remove WWW from domain URL in NGINX.
How To Remove WWW from Domain URL in NGINX
Here are the steps to remove WWW from domain URL in NGINX.
1. Open NGINX configuration file
Open terminal and run the following command to open NGINX server configuration file.
$ sudo vi /etc/nginx/nginx.conf
If you have configured separate virtual hosts for your website (e.g www.example.com), such as /etc/nginx/sites-enabled/website.conf then open its configuration with the following command
$ sudo vi /etc/nginx/sites-enabled/website.conf
Alternatively, you can also open the default virtual host configuration file.
$ sudo vi /etc/nginx/sites-enabled/default
Also read : How to Redirect WWW to Non-WWW URLs
2. Redirect WWW to Non-WWW
You will need to create two server blocks in NGINX configuration – one for www and another for non-www.
In server block for www, we will redirect all URLs to non-www server block.
Here is the full configuration for it. Replace example.com with your domain name.
server { server_name www.example.com; return 301 $scheme://example.com$request_uri; } server { server_name example.com; ... }
The first server listens to URLs starting with www.example.com and redirects them to URLs starting with example.com, which is handled by the second server.
Also Read : How to Configure Basic Authentication in NGINX
3. Restart NGINX Server
Run the following command to check syntax of your updated config file.
$ sudo nginx -t
If there are no errors, run the following command to restart NGINX server.
$ sudo service nginx reload #debian/ubuntu $ systemctl restart nginx #redhat/centos
Hopefully, this article will help you redirect WWW to Non-WWW URLs in NGINX. Ubiq makes it easy to visualize data, and monitor them in real-time dashboards. Try Ubiq for free.