Skip to content

Whitelisting IP Addresses

Some times we need to let certain services through a firewall or strict rule set in Nginx. There are some good tools to allow us to do this.

The primary use case for doing this is to allow certain third parties to be able to make API calls for things to work correctly.

Note

We are assuming that Nginx has the Geo module installed

Outside of any server blocks, you can use a geo directive to map an IP address to a value. For example

geo $safeIp {
    127.0.0.1 1;
    10.0.0.1 1;
    default 0; # Defaults to this value when no match is found
}

The result of the $safeIp variable is dependent on the client IP address and can then be used in an if condition in your location blocks.

if ($safeIp)
{
    return 200;
}

proxy_pass http://some-service;

Debugging the variables

When things are not working correctly, we can use the add_header call to append our Nginx variables to responses.

add_header "X-DEBUG-MYWHITELIST" "$safeIp";