Introduction

Redirecting non-www requests to www is a common web server configuration used to maintain a consistent website URL. Nginx can handle this redirection using a simple server block configuration. This helps ensure that visitors accessing the website without www are automatically redirected to the www version. A permanent 301 redirect can also help search engines recognize the preferred URL. This article explains how to configure Nginx to redirect non-www requests to www.

Prerequisites

  • Nginx installed and running on the server.
  • A valid domain name configured on the server.
  • Access to the Nginx configuration files.
  • Root or sudo privileges.
  • Basic knowledge of Nginx configuration.

IMPLEMENTATION

If you followed the above posts, the default location of the Nginx configuration isĀ /etc/nginx/sites-enabled/default.

Open the Nginx configuration and add the following lines.

vi /etc/nginx/sites-enabled/default

server {
    listen 80;
    server_name domain.tld;

    return 301 http://www.domain.tld$request_uri;
}

Check for syntax errors

nginx -t

If there is no error, restart the Nginx service to make the changes take effect.

/etc/init.d/nginx restart

Conclusion

Configuring Nginx to redirect non-www requests to www is a simple and effective way to maintain a consistent website URL. A 301 redirect ensures that requests are automatically sent to the preferred www version. Before applying the changes, the Nginx configuration should be tested using nginx -t. Once the configuration is validated, restarting or reloading Nginx applies the changes. This approach also helps maintain consistent URL handling across the website.

Leave a Reply