How to Redirect All Except Your IP Address using NGINX


redirect all except your ip address using nginx

Sometimes, when you redirect a page to a different, you might need to exclude a few known IPs. Here’s how to redirect all except your IP address using NGINX.

 

How to Redirect All Except Your IP Address using NGINX

Here are the steps to redirect all except your IP address using NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. It is typically located at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Redirect all except your IP address

Let’s say you want to redirect all IPs except yours (192.168.0.1) from /login.php to /product-page.php. So add the following lines to your nginx.conf file


location /login.php {
 if ($remote_addr != 192.168.0.1) {
  rewrite ^ /product-page.php last;
 }
}

 

The above location checks for the IP address for each request, and redirects only if it doesn’t match your own IP address.

 

You can use the above solution to direct all visitors to maintenance page (/maintenance.php)


location / {
 if ($remote_addr != 192.168.0.1) {
  rewrite ^ /maintenance.php last;
 }
}

Let’s say you want to redirect all except a few multiple IPs, then use the ‘|’ operator to combine the IP addresses as shown


location /login.php {
 if ($remote_addr ~ (192.168.0.1 | 127.0.0.1) {
  rewrite ^ /product-page.php last;
 }
}

 

If you want to allow a range of IP addresses (192.168.0.1 – 192.168.0.255), use the CIDR notation, instead of providing an IP address, as shown


location /login.php {
 if ($remote_addr ~ (192.168.0.0/24) {
  rewrite ^ /product-page.php last;
 }
}

 

3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

 

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!