How can i check if $remote_addr IP is NOT in CIDR range in nginx?
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;
}
....
}