How to Block Foreign IPs with Nginx Using the ngx_http_geoip2 Module
This guide walks through installing the GeoIP2 library, compiling Nginx with the ngx_http_geoip2 module, downloading the latest MaxMind database, and configuring Nginx to reject requests from non‑Chinese IP addresses, complete with command‑line examples and verification steps.
Introduction: The author noticed many malicious requests from foreign IPs in the Nginx access log and decided to block them using the ngx_http_geoip2 module.
1. Install GeoIP2 dependencies
[root@fxkj ~]# yum install libmaxminddb-devel -y2. Download the ngx_http_geoip2_module
[root@fxkj tmp]# git clone https://github.com/leev/ngx_http_geoip2_module.git3. Extract the module to a target directory
The module is moved to /usr/local and its contents are listed.
4. Install/upgrade Nginx with the module
The current Nginx version is 1.16; the module requires at least 1.18, so Nginx is upgraded to 1.18 and compiled with the GeoIP2 module.
Download Nginx 1.18
Extract the package and configure with --add-module=/usr/local/ngx_http_geoip2_module Run make and replace the old binary (backup first)
Restart Nginx
5. Download the latest IP database
After installing the module, a MaxMind GeoIP database must be placed in /usr/share/GeoIP/. The user creates a MaxMind account, downloads the GeoLite2 Country GZIP file, and extracts it to the directory.
6. Configure Nginx
Backup the existing nginx.conf and edit it. In the http block, add:
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;
}In the server location block, add a condition to return 404 for foreign IPs:
if ($allowed_country = yes) {
return 404;
}Test the configuration with nginx -t and reload.
7. Test the setup
Using a server located abroad (e.g., Korea), the request returns a 404 error, confirming that foreign IPs are blocked. The Nginx access log shows the 404 response.
Thus, the tutorial demonstrates how to block foreign IP addresses in Nginx using the ngx_http_geoip2 module.
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.
Linux Cloud Computing Practice
Welcome to Linux Cloud Computing Practice. We offer high-quality articles on Linux, cloud computing, DevOps, networking and related topics. Dive in and start your Linux cloud computing journey!
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.
