NGINX – Redirecting traffic between www and non-www domain


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

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

This entry was posted in Devops and tagged , , , . Bookmark the permalink.

5 Responses to NGINX – Redirecting traffic between www and non-www domain

  1. Pingback: NGINX – Load Balancing your application made simple | Knoldus

  2. Pingback: NGINX – Restrict access to Geographical Locations using GeoIP module | Knoldus

  3. Pingback: NGINX – Disable direct access (via http and https) to a website using IP address | Knoldus

  4. Pingback: NGINX – Easiest way to setup SSL on using .pfx files | Knoldus

  5. Pingback: NGINX – Redirecting HTTP to HTTPS | Knoldus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s