NGINX – Redirecting traffic between www and non-www domain

Table of contents
Reading Time: < 1 minute

Just in case you ever wondered whether the re-routing from www to non-www or non-www to www domain is possible using NGINX then you bet it is! In fact it is very simple and can be done using the following steps

1. Redirecting from www to non-www
Setup a initial virtual server block to point your domain to your content, a simple example would look something like this:

server {
 listen 80;
 server_name example.com;

 root /path/to/your/content/;
 index index.html;
 include /etc/nginx/mime.types;
}

Other NGINX blogs you might find useful

  1. NGINX – Load Balancing your application made simple
  2. NGINX – Restrict access to Geographical Locations using GeoIP module
  3. NGINX – Disable direct access (via http and https) to a website using IP address
  4. NGINX – Redirecting HTTP to HTTPS
  5. NGINX – Easiest way to setup SSL on using .pfx files
  6. NGINX – Understanding and Setting up a reverse proxy server

and then setup another virtual server block for the redirect

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

which will simply redirect the traffic from http://www.example.com to http://example.com.

2. Redirecting from non-www to www
I believe by now you might have understood how it works and doing the reverse is even more easy which is by using the following instructions

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

server {
 listen 80;
 server_name www.example.com;

 root /path/to/your/content/;
 index index.html;
 include /etc/nginx/mime.types;
}

knoldus-advt-sticker

Written by 

Sidharth is a Lead Consultant, having experience of more than 4.5 years. He has started working on Scala and Clojure and is actively involved in other developmental work. He enjoys working in a team and believes that knowledge is something that should be shared openly and on a large scale. As an avid gamer and passionate player, he likes to be involved in both indoor and outdoor activities.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading