nginx url redirect

Sometimes you want to maintain uniform URL requiring to permanently redirect a URL eg. Redirecting parent domain to www prefixed domain or vice versa. Their can be also a case where you have multiple domain names and you want to redirect all traffic to single domain.

In Nginx it can be done with a simple rewrite statement within the new or existing configuration file. Lets assume we have a domain abc.com and we want every request to get redirected towards www.abc.com.

server {
server_name abc.com;
rewrite ^ http://www.abc.com$request_uri? permanent;
}

In the above line of configuration code it is entertaining request directed towards abc.com , rewrite directive is forcing the request to get redirected towards www.abc.com domain. Variable request_uri is passing the values to www domain which is passed by user client.

Permanent is appended to the url specifying that it is a 301 permanent redirect rather then 302 temporary redirect.