How to Redirect based on IP address in NGINX


redirect based on ip address in nginx

When you run a website, you might need to redirect visitors from a specific IP address or even an address range to a different web page, subdomain or a different domain. This is an effective way to provide a customized user experience. NGINX allows you to accomplish this with the help of $remote_addr server variable that stores the IP address of requesting client. Let us take a look at how to redirect based on IP address in NGINX.

 

How to Redirect based on IP address in NGINX

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

Let’s say you want to redirect traffic from a specific IP address 192.168.1.1 from /login.php to /new-login.php then add the following Iif condition to your location block for /login.php


location /login.php{
 if ( $remote_addr ~* 192.168.1.1 ) {
   return 301 /new-login.php;
 }
}

location /new-login.php{
#config for /new-login.php;
}

 

If you want to redirect based on IP range, use the Geo module. In this case, you need to specify IP ranges using the CIDR notation. You can use one of the online tools to get the CIDR notation for your IP range.

geo $redirect_user {
  default 0;
  192.168.0.0/24 1;
  54.45.34.12/32 1;
}

server {
location /login.php{
 if ( $redirect_user ) {
   return 301 /new-login.php;
 }
}

location /new-login.php{
 #config for /new-login.php;
}

}

 

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! NGINX will now automatically redirect website visitors based on their IP addresses.

 

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!