How to Redirect NGINX Requests to WWW from non-WWW

Overview

In this tutorial, you will learn how to use redirects in NGINX to force traffic onto a www domain. This is common when optimizing for SEO or using non-wildcard TLS hostnames, for example.

HTTP Redirects

There are two types of redirects possible with HTTP requests. The first one is a STATUS 302, which is used temporarily when a site under maintenance, or is being hosted from a temporary platform.

The second type of redirect is a STATUS 301, which is a permanent redirect. This instructs web browsers and web crawlers that the entered URL is no longer valid, and that the content has permanently moved.

Redirect non-WWW to WWW

To redirect the traffic, NGINX must first listen for requests that are non-WWW. We do this be creating a listener to capture this type of traffic. Once caught, the traffic is redirected to the proper hostname.

Catch non-WWW Traffic

The following example NGINX virtual server will listen for the non-WWW traffic of a domain named serverlab.ca.

server {
  listen 80;
  server_name serverlab.ca
  return 301 http://www.serverlab.ca$request_uri;
}

The virtual server above listens on port 80 for any requests targeting serverlab.ca. Any traffic caught by this listener is then redirected using the return directive.

The return direct sets the status to 301 to communicate that the content has moved permanently. At return directive contains a variable $request_uri, which is appended to the target URL. This instruct NGINX to append the entire URI of the incoming request to the redirect.

Listen for WWW Traffic

NGINX must also listen for WWW traffic. We create a second virtual server to handle this requests.

server {
  listen 80;
  server_name www.serverlab.ca

  location / {
    proxy_pass http://backend
  }
}

upstream backend {
  ip_hash;
  server app01:8080;
  server app02:8080;
}

Testing the Redirect

Redirects can be tested by using an web client, such as a web browser or the curl command. Redirecting from non-WWW to WWW is visible enough from a browser.

Using a command like, however, provides much more details into how the request is being handled. To verify the redirect is working correctly, you would use the following command.

curl -IL http://serverlab.ca/

The output of the command would look similar to the following example. The key line item to watch for is the HTTP/1.1 301 Moved Permanently line. This let’s us know the redirect is working as expected.

HTTP/1.1 301 Moved Permanently
Server: nginx/1.14.0 (Ubuntu)
Date: Wed, 29 May 2019 03:43:15 GMT
Content-Type: text/html
Content-Length: 10918
Last-Modified: Mon, 27, May 2019 22:49:05 GMT
Connection: keep-alive