How to Block Foreign IPs in NGINX Using the GeoIP2 Module
This guide walks you through installing the GeoIP2 dependencies, adding the ngx_http_geoip2 module to NGINX, upgrading NGINX, downloading the latest GeoIP2 database, configuring NGINX to block non‑Chinese IPs, and verifying the setup with test requests.
1. Install GeoIP2 dependencies
yum install libmaxminddb-devel -y2. Download ngx_http_geoip2_module
git clone https://github.com/leev/ngx_http_geoip2_module.git3. Extract module to /usr/local
mv ngx_http_geoip2_module/ /usr/local/4. Upgrade NGINX to 1.18 and compile with the module
Download NGINX 1.18 source package.
Configure with --add-module=/usr/local/ngx_http_geoip2_module and other required flags.
Run make, backup the existing binary, and replace it with the newly built one.
# Example commands
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/nginx.bak
cp objs/nginx /usr/local/nginx/sbin/5. Download the latest GeoIP2 database
Register at MaxMind , download the GeoLite2 Country database, and unzip it into /usr/share/GeoIP/.
6. Configure NGINX
Backup the existing nginx.conf and add the following directives.
geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
auto_reload 5m;
$geoip2_data_country_code country iso_code;
}
map $geoip2_data_country_code $allowed_country {
default yes;
CN no;
}
if ($allowed_country = yes) {
return 404;
}Test the configuration with /usr/local/nginx/sbin/nginx -t and reload NGINX.
7. Verify the blocking
Access the site from a foreign IP (e.g., a Korean server). The request should return a 404 response, and the NGINX access log will show the blocked request.
13.125.1.194 - - [14/Aug/2020:16:15:51 +0800] "GET /favicon.ico HTTP/1.1" 404 548 "https://www.fxkjnj.com/" "Mozilla/5.0 ..."Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
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.
