How to set up Nginx to automatically redirect www to non-www URLs or vice versa?

To set up Nginx to automatically redirect www to non-www or vice versa, you can follow these steps:

  1. Connect to your server via SSH.
  2. Open your Nginx configuration file for the relevant website. This file is typically located in the /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.
  3. Edit the configuration file using a text editor such as nano or vi. sudo nano /etc/nginx/sites-available/example.com.conf
  4. Inside the 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; }
  5. Save the file and exit the text editor.
  6. Test your Nginx configuration file for any syntax errors: sudo nginx -t If there are no errors, continue to the next step. Otherwise, fix the errors in your configuration file and test again.
  7. Once the configuration file is error-free, reload Nginx to apply the changes: sudo systemctl reload nginx
  8. Verify that the redirection is working by accessing your website using both www and non-www URLs. The redirection should be automatic and seamless.

By following these steps, Nginx will redirect visitors to either the www or non-www version of your website, depending on your configuration.