How to Redirect based on Referrer in NGINX

redirect based on referrer in nginx

When running a website, you might want to redirect users to specific landing pages, based on where they come from. You might also want to block malicious bots and website traffic. You can easily do all this in NGINX with the help of environment variable $http_referrer. Let us take a look at how to redirect based on referrer in NGINX.


How to Redirect based on Referrer in NGINX

Here are the steps to redirect based on referrer 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



$ sudo vim /etc/nginx/nginx.conf


2. Redirect based on Referrer

Let’s say you want to redirect all traffic coming from to a different subdomain then add the following lines of code to location block of your NGINX config file where you want redirection to happen

location / {
 if ($http_referer ~* ^$ ) {
    return 301


If you want to preserve the query string,

if ($http_referer ~* ^$ ) {
    return 301$1


If you want to redirect based on multiple referrers then, use regular expressions,

if ($http_referer ~* ^[a-z]{2,3}(.[a-z]{2})?$ ) {
    return 301$1

The above code will redirect all traffic from google to


Here’s another example,

if ($http_referer ~* (| ) {
    return 301$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 incoming traffic based on their http referrer in request headers.

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!