11

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 .

1 Answer 1

22

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;
    }
    ....
}
1
  • 1
    Its working as expected , blocking everybody else with 444 and only allowing ips which are in CIDR range . i really appreciate it.
    – user138870
    Dec 16, 2015 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy