ScaleScaleScaleScale

Tips / Nginx


How to Redirect Nginx traffic based on the Client’s IP Address

Sometimes developers need to redirect part of their traffic to another web area or specific URL. Depending on the IP address the visitors have, it’s ideal to geo-locate traffic or simply protect areas from unwanted specific IP addresses. So, how do you redirect traffic from IP 1.2.3.4 to http://www.thisurl.com/page2.html and the rest of the traffic to http://www.thisurl.com/? We’ll go over this today.

Redirect using Nginx HttpAccessModule

As Nginx supports conditional configurations, first let’s look at an example of how to redirect traffic using HttpAccessModule running a regex against $remote_addr variable.

server {
if ($remote_addr = 1.2.3.4) {
rewrite ^ http://www.yourwebsite.com/otherpage.htm;
}
}

In this example, 1.2.3.4 is the IP address you want to redirect.

What if you are using Nginx as front end proxy for Apache?

In this case you can do almost the same thing, redirecting the traffic to the backend servers:

if ( $remote_addr = 1.2.3.4 ) {
proxy_pass http://www.yourwebsite.com/otherpage.htm;
}

Real life examples of this include uploading a maintenance page for the rest of your office connections, and driving all the traffic there while working on your live website. Or to allow access to protected admin areas just for your IP, leaving the rest of the network without access. (From a security point of view, you should also add user and password protection.)

Redirect using Nginx Geo Module

The second alternative we have to do this is by using the Nginx Geo module. This will create variables depending on your visitor’s IP address.

Usage example:

geo $bad_user {
default 0;
1.2.3.4/32 1;
}

server {
if ($bad_user) {
rewrite ^ http://www.yourwebsite.com/otherpage.html;
}

In this example, default 0 means the value is set to the variable if the client address doesn’t match any of the specified addresses. The other value is the IP address you want to match that will be redirected later.

Popular search terms:

  • https://www scalescale com/tips/nginx/redirect-nginx-traffic-client-ip/#
  • nginx map ip
  • nginx redirect based on ip
  • nginx geo redirect
profile

Esteban Borges

Linux Geek, Webperf Addict, Nginx Fan. CTO @Infranetworking