Advertisments

NGINX – Redirecting traffic between www and non-www domain

Tuesday, May 01, 2018

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;
}
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;
}
This article was first published on the Knoldus blog.

You Might Also Like

0 comments

Like us on Facebook

Featured Post

Beginners guide to Deep Web or Darknet

UPDATED  on 12th May 2018 The "Deep Web" or "Darknet" is a collection of un-indexed pages, meaning you can't fin...