How can i check if $remote_addr IP is NOT in CIDR range in nginx?

AMB asked:

I am using nginx latest web server.
How can i check if the $remote_addr ip is NOT in specified CIDR range and return appropriate error code.

i would like to return specific error codes if IP is NOT in specific CIDR IP ranges.

how can i do this for CIDR IP range ?
e.g.

  • If remote_addr is not in 123.123.123.123/24 then return 444 code .

My answer:


You can use the geo directive to specify IP address ranges.

Here’s an example:

geo $block_these_turkeys {
    default         0;
    192.0.2.0/24    1;
    198.51.100.0/24 1;
    203.0.113.0/24  1;
    2001:db8::/32   1;
}

This must be in the http block, outside of any server block.

It sets the variable $block_these_turkeys to the given value, based on whether the IP address matches one of the listings.

Later, in the server block where you want to use it, do something like:

server {
    ....
    if ($block_these_turkeys) {
        return 444;
    }
    ....
}

By reversing the value, you can allow IP ranges instead.

geo $block_almost_everybody {
    default         1;
    192.0.2.0/24    0;
    198.51.100.0/24 0;
    203.0.113.0/24  0;
    2001:db8::/32   0;
}

server {
    ....
    if ($block_almost_everybody) {
        return 444;
    }
    ....
}

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.