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


/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 Referrer

Let’s say you want to redirect all traffic coming from stackoverflow.com to a different subdomain so.domain.com 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 ~* ^www.stackoverflow.com$ ) {
    return 301 http://so.domain.com
 }
}

 

If you want to preserve the query string,

if ($http_referer ~* ^www.stackoverflow.com$ ) {
    return 301 http://so.domain.com/$1
}

 

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

if ($http_referer ~* ^www.google.[a-z]{2,3}(.[a-z]{2})?$ ) {
    return 301 http://so.domain.com/$1
}

The above code will redirect all traffic from google to so.domain.com

 

Here’s another example,

if ($http_referer ~* (www.google.com|www.yahoo.com) ) {
    return 301 http://so.domain.com/$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!