Redirect non-www and www URLs on Nginx

Updated on November 21, 2023
Redirect non-www and www URLs on Nginx header image

Introduction

You may run a website on the www or non-www address as a personal preference, but to prevent redundant hostnames it's recommended to choose one style and be consistent throughout your site. Whichever address you choose, you should make a permanent HTTP 301 redirect from the other address to prevent Google Analytics from logging it as a redundant hostname.

This article describes how to configure Nginx to redirect a non-www URL to the www address, and vice-versa.

Prerequisites

  • You have a Vultr Linux instance running Nginx.
  • You have a domain name such as example.com whose DNS A records for "@" and "www" are pointing to the IP address of the Vultr instance.

Nginx Hosting a Single Domain

How to Redirect non-www to www

  1. Locate your virtual host configuration file, which is typically located in /etc/nginx/sites-available.

  2. Add an new server block at the top, above the existing server block, like:

     server {
         listen 80;
         server_name example.com;
         return 301 $scheme://www.example.com$request_uri;
     }

    This directive tells Nginx to send any request for http://example.com to http://www.example.com with HTTP redirect code 301.

  3. Restart Nginx to apply the change. Ubuntu or Debian systems use the command:

     $ sudo systemctl restart nginx

How to Redirect www to non-www

  1. Locate your virtual host configuration file, which is typically located in /etc/nginx/sites-available.

  2. Add an new server block at the top, above the existing server block, like:

     server {
         listen 80;
         server_name www.example.com;
         return 301 $scheme://example.com$request_uri;
     }

    This directive tells Nginx to send any request for http://www.example.com to http://example.com with HTTP redirect code 301.

  3. Restart Nginx to apply the change. Ubuntu or Debian systems use the command:

     $ sudo systemctl restart nginx

Nginx Hosting Multiple Domains

If your Nginx server is hosting multiple domains, use this method to match all domain names.

To redirect the non-www URL to the www address for all domains, add this snippet inside the http directive in your nginx.conf file, which is usually located in /etc/nginx.

server {
    server_name "~^(?!www\.).*" ;
    return 301 $scheme://www.$host$request_uri;
}

Or, to redirect the www URL to the non-www address for all domains, add this snippet inside the http directive in your nginx.conf file, which is usually located in /etc/nginx.

server {
    server_name "~^www\.(.*)$" ;
    return 301 $scheme://$1$request_uri ;
}

Restart Nginx to apply the change. Ubuntu or Debian systems use the command:

$ sudo systemctl restart nginx