Nginx: Redirect Backend Traffic Based Upon Client IP Address

Nginx: Redirect Backend Traffic Based Upon Client IP Address

To redirect backend traffic based on the client's IP address in Nginx, you can use the geo module and the proxy_pass directive. Here's an example of how you can redirect traffic to different backend servers based on the client's IP address:

refer‮ual:ot ‬tturi.com
geo $backend {
    default backend1;
    1.2.3.4 backend2;
    5.6.7.8 backend3;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://$backend;
    }
}

In this example, the geo block defines a variable called $backend that will be set to one of three values based on the client's IP address: backend1, backend2, or backend3. The default value for $backend is backend1, which means that all clients not explicitly listed in the geo block will be sent to the backend1 server. Clients with an IP address of 1.2.3.4 will be sent to the backend2 server, and clients with an IP address of 5.6.7.8 will be sent to the backend3 server.

The proxy_pass directive in the location block specifies that traffic should be forwarded to the backend server specified by the $backend variable.

You can add as many IP addresses and backend servers as you like to the geo block. You can also use CIDR notation to specify a range of IP addresses, for example:

geo $backend {
    default backend1;
    1.2.3.0/24 backend2;
    5.6.7.8 backend3;
}

In this example, all clients with an IP address in the range 1.2.3.0 to 1.2.3.255 will be sent to the backend2 server.

For more information on the geo module and the proxy_pass directive, you can refer to the Nginx documentation.

Created Time:2017-10-30 10:17:52  Author:lautturi