To set up Nginx to automatically redirect www to non-www or vice versa, you can follow these steps:
/etc/nginx/sites-available/
directory and has a .conf
extension. For example, if your website name is example.com
, the file would be named example.com.conf
.sudo nano /etc/nginx/sites-available/example.com.conf
server
block, add the following code to redirect www to non-www URLs:
server {
listen 80;
server_name www.example.com;
return 301 http://example.com$request_uri;
}
Alternatively, to redirect non-www to www URLs, use the following code:
server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
sudo nginx -t
If there are no errors, continue to the next step. Otherwise, fix the errors in your configuration file and test again.sudo systemctl reload nginx
By following these steps, Nginx will redirect visitors to either the www or non-www version of your website, depending on your configuration.