Tuesday, May 1, 2018

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;
}
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.

No comments:

Post a Comment