How to Redirect based on URL in NGINX


redirect based on url in nginx

When you move your website or some of its pages, you need to redirect old URLs to new ones, so that both website visitors and search engines know that your content has moved. You can easily accomplish this in NGINX. Let us take a look at how to redirect based on URL in NGINX.

 

How to Redirect based on URL in NGINX

Here are the steps to redirect based on URL in NGINX.

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Redirect based on URL

Let’s say you want to redirect a specific url /docs/getting-started to another url /how-to-redirect on the same website, then add the following code to your NGINX config file.


location = /docs/getting-started {
 return 301 /how-to-redirect/
}

 

You can also use the full URL for destination of redirection


location = /docs/getting-started {
 return 301 http://example.com/how-to-redirect/
}

 

If you want to all URLs in a specific folder /docs/ to another folder /articles/


location /docs {
 return 301 /articles
}

In the above code, please note that there is no ‘=’ after location directive.

 

If you want to create a temporary redirect, add ‘302’ after return directive, instead of using 301.

 

If you want to redirect a specific URL pattern,


location ~ ^/docs/(.*) {
 rewrite ^ /articles/$1;
}

 

If you want to redirect old URLs to a new domain (e.g www.new-domain.com) altogether, then use the domain name in your rewrite statement.


location ~ ^/docs/(.*) {
 rewrite ^ http://www.new-domain.com/articles/$1;
}

 

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! Now NGINX will automatically redirect website visitors and search engine bots based on their requested URL.

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!