How to Redirect based on Host Name in NGINX


redirect based on host name in nginx

When you receive traffic from a few specific websites, you can personalize user experience by creating specific landing pages/subdomains and redirecting your website visitors based on their host name. NGINX allows you to do this easily with the help of server environment variable $host. Let us take a look at how to redirect based on host name in NGINX.

 

How to Redirect based on Host Name in NGINX

Here are the steps to redirect based on host name 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 Host Name

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 ($host ~* ^www.stackoverflow.com$ ) {
    return 301 http://so.domain.com
 }
}

 

If you want to preserve the query string,

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

 

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

if ($host ~* ^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 websites to so.domain.com

 

Here’s another example,

if ($host ~* (www.google.com|www.yahoo.com) ) {
    return 301 http://so.domain.com/$1
}

In this case all traffic coming from google and yahoo are redirected.

 

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 host 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!