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 to and the rest of the traffic to 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 = {
rewrite ^;

In this example, 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 = ) {

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;

server {
if ($bad_user) {
rewrite ^;

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

Esteban Borges

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