Backend Development 7 min read

Blocking Foreign IP Access with Nginx Using the ngx_http_geoip2 Module

This tutorial explains how to prevent overseas IP addresses from reaching a website by installing the libmaxminddb-devel dependency, adding the ngx_http_geoip2 module to Nginx, upgrading to Nginx 1.18, configuring GeoIP2 database paths, mapping country codes, and returning a 404 response for foreign requests.

Architecture Digest
Architecture Digest
Architecture Digest
Blocking Foreign IP Access with Nginx Using the ngx_http_geoip2 Module

The author noticed a large number of malicious foreign IP requests in Nginx access logs and decided to block all non‑Chinese traffic.

First, the required library is installed:

yum install libmaxminddb-devel -y

Then the GeoIP2 module source is cloned and moved to /usr/local/ngx_http_geoip2_module :

git clone https://github.com/leev/ngx_http_geoip2_module.git
mv ngx_http_geoip2_module/ /usr/local/

Because the current Nginx (1.16) does not support the module, the author upgrades to Nginx 1.18, extracts the source, and compiles it with the added module:

tar -xf nginx-1.18.0.tar.gz
cd nginx-1.18.0/
./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
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx1.16   # backup
cp objs/nginx /usr/local/nginx/sbin/                     # replace
pkill nginx && /usr/local/nginx/sbin/nginx                # restart

The latest GeoLite2 Country database is downloaded from MaxMind, placed under /usr/share/GeoIP , and the file GeoLite2-Country.mmdb is ready for use.

Configuration changes are added to nginx.conf (after backing it up). In the http block:

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;
}

And inside the relevant server location block:

if ($allowed_country = yes) {
    return 404;
}

The configuration is tested with nginx -t , reloaded, and a request from a Korean IP is shown to receive a 404 Not Found response, confirming that foreign IPs are successfully blocked.

Finally, the author checks the Nginx access log to verify that the blocked request is logged as a 404 entry.

backendLinuxsecuritynginxGeoIP2IP blocking
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.