Block or filter IPs based on location except lan ips in Nginx (tested on 1.22.1) on Debian 12.
To make use of the geographical filtering, we must first install the Nginx GeoIP module as well as the GeoIP database containing the mappings between visitors’ IP addresses and their respective countries. To do so, let’s execute:
$ sudo apt install libnginx-mod-http-geoip geoip-database
Edit nginx config /etc/nginx/nginx.conf
. Add this below the http {
line to only allow Russian IPs You can use ISO’s full, searchable list of all country codes to find your code.
# lan IPs
geo $lan {
default 0;
1.2.3.4 1;
}
# GeoIP database path
geoip_country /usr/share/GeoIP/GeoIP.dat;
# Allowed country codes
map $geoip_country_code $allowed_country {
default 0;
RU 1;
}
map $lan$allowed_country $deny {
default 0;
00 1;
}
Finally, add this to your sites virtual config /etc/nginx/sites-enabled/siteconfig
below server {
:
if ($deny) {
return 503;
}
Check Nginx config sudo nginx -t
Reload Nginx sudo systemctl restart nginx.service