How to Block Foreign IPs with NGINX and the ngx_http_geoip2 Module
This step‑by‑step guide shows how to install the GeoIP2 library, compile NGINX 1.18 with the ngx_http_geoip2 module, download the latest MaxMind GeoLite2 database, configure geoip2 directives, and verify that foreign IP requests are blocked with a 404 response.
Install GeoIP2 library
yum install libmaxminddb-devel -yObtain the ngx_http_geoip2_module source
git clone https://github.com/leev/ngx_http_geoip2_module.gitPlace the module in a permanent directory
mv ngx_http_geoip2_module/ /usr/local/Upgrade NGINX to version 1.18 (or later) and compile with the GeoIP2 module
Download the NGINX 1.18 source tarball and extract it.
Ensure libmaxminddb-devel is installed (step 1).
Configure the build, adding the module path:
./configure \
--with-http_stub_status_module \
--prefix=/usr/local/nginx \
--user=nginx --group=nginx \
--with-http_ssl_module \
--with-stream \
--add-module=/usr/local/ngx_http_geoip2_module
make
# Backup the existing binary
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
# Replace with the newly built binary
cp objs/nginx /usr/local/nginx/sbin/nginx
# Restart NGINX
pkill nginx
/usr/local/nginx/sbin/nginxDownload the GeoLite2‑Country database
Create a free account at https://www.maxmind.com, download the GeoLite2‑Country GZIP file, and extract it to /usr/share/GeoIP/. The extracted file should be named GeoLite2-Country.mmdb.
Configure NGINX
Backup the current configuration before editing.
cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak
vim /usr/local/nginx/conf/nginx.confAdd the following directives inside the http block to load the database and map country codes:
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
auto_reload 5m;
$geoip2_data_country_code country iso_code;
}
map $geoip2_data_country_code $allowed_country {
default yes;
CN no;
}Within the desired server block (e.g., inside a location), block foreign IPs:
if ($allowed_country = yes) {
return 404;
}Validate the configuration
/usr/local/nginx/sbin/nginx -tReload NGINX: /usr/local/nginx/sbin/nginx -s reload Test from an overseas IP (e.g., a Korean server). The request should return 404 Not Found. Verify the entry in the access log, for example:
13.125.1.194 - - [14/Aug/2020:16:15:51 +0800] "GET /favicon.ico HTTP/1.1" 404 548 "https://www.example.com/" "Mozilla/5.0 ... Chrome/84.0.4147.125 Safari/537.36"With these steps, NGINX blocks requests originating from non‑Chinese IP addresses using the ngx_http_geoip2 module.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
