Sling Academy
Home/DevOps/NGINX: How to Redirect non-www to www (and Vice Versa)

NGINX: How to Redirect non-www to www (and Vice Versa)

Last updated: January 19, 2024

Introduction

Consistency in how URLs are accessed is key for branding and SEO purposes. NGINX, a high-performance web server, makes URL redirection from non-www to www domains (or vice versa) straightforward. This tutorial will guide you through the process of setting up these redirections in NGINX with various examples that progress from basic to advanced configurations.

Understanding NGINX Server Blocks

Before diving into redirections, it’s essential to understand server blocks in NGINX, akin to virtual hosts in Apache. They allow you to host multiple websites on a single server by listening to requests for certain domains or IP addresses and serving the appropriate content.

Basic Redirection: non-www to www

To start with a basic redirection from a non-www to a www domain, edit your NGINX configuration file typically found at /etc/nginx/sites-available/your_domain.

server {
    server_name example.com;
    return 301 http://www.example.com$request_uri;
}

This block checks for requests matching example.com and redirects them to www.example.com using a 301 permanent redirect, preserving the request URI.

Redirecting www to non-www

Just as one can redirect non-www to www, reversing it is equally simple. The server block would look like this:

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

This configuration ensures that any request to www.example.com is permanently redirected to example.com, maintaining the protocol (HTTP or HTTPS) used in the initial request.

Handling HTTPS Traffic

With the increasing need for secure connections, handling HTTPS traffic becomes necessary. The example below demonstrates the redirection from non-www to www over HTTPS.

server {
    listen 443 ssl;
    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/key.pem;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/key.pem;
    server_name www.example.com;
    # Your normal web content block goes here
}

The first server block handles the SSL connection for the non-www version of the site and redirects all traffic to the www version. The second server block is configured to serve web content for the www version.

Wildcard Redirects

In more complex scenarios where a website may have multiple subdomains, a wildcard redirect might become necessary. The NGINX server block configuration can employ a regular expression to match subdomains:

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

This block captures anything that follows www. using regular expressions and redirects to the non-www version at the captured domain.

Using Maps for Dynamic Redirection

If you manage multiple sites or need a more dynamic solution, you can use the map directive outside the server block:

map $http_host $newhost {
    ~^www\.(.*)$  $1;
    ~^(?!www\.)(.*)$  www.$1;
}

server {
    if ($newhost != '') {
        rewrite ^ $scheme://$newhost$request_uri? permanent;
    }
    # Other configuration directives...
}

With map, we define a variable $newhost based on the presence or absence of www and redirect the request accordingly in the server block using a conditional rewrite.

Testing and Troubleshooting

After making changes to the NGINX configuration, always test the config with nginx -t and reload the server using systemctl reload nginx or service nginx reload. If any issues arise, review logs typically located at /var/log/nginx/error.log.

Conclusion

In this tutorial, we have covered methods to set up redirection from non-www to www and vice versa in NGINX. Whether you are handling simple domains or managing complex scenarios with multiple subdomains, NGINX provides efficient configuration options to achieve the required redirections.

Next Article: NGINX: How to Block a List of IP Addresses

Previous Article: NGINX Server Blocks: The Complete Guide

Series: NGINX Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide