nginx 默认不编译 geoip 模块,需通过 nginx -v 检查 with-http_geoip_module;1.11.3+ 应改用 geoip2 模块配合 geolite2 .mmdb 数据库,并用 map + if 实现地域拦截,注意 real_ip 配置与数据库热更新。

确认 Nginx 是否已编译 GeoIP 模块
很多发行版预装的 nginx(尤其是 apt/yum 仓库里的)默认不带 ngx_http_geoip_module,哪怕你装了 libgeoip1 或 geoip-database 也没用。直接运行 nginx -V 2>&1 | grep -o with-http_geoip_module,如果没输出,说明模块根本没编译进去。
解决路径只有两条:
– 重装支持该模块的包(如 Ubuntu 的 nginx-full,而非 nginx-light);
– 或从源码重新编译,configure 时显式加上 --with-http_geoip_module(注意:Nginx 1.11.3+ 已废弃该模块,改用 ngx_http_geoip2_module,下文会提)。
常见错误现象:unknown directive "geoip_country" 或 nginx: [emerg] unknown directive "geoip_city",基本都源于此。
用 geoip2 模块替代旧版 geoip(Nginx ≥1.11.3 必须)
旧 ngx_http_geoip_module 仅支持 GeoLite Legacy 格式(.dat),官方早在 2018 年停更;现在必须用 ngx_http_geoip2_module + GeoLite2 数据库(.mmdb)。它需要额外安装 libmaxminddb 和模块本身(通常需手动编译进 Nginx)。
实操要点:
- 下载
GeoLite2-Country.mmdb到本地(如/usr/share/GeoIP/GeoLite2-Country.mmdb),注意权限要让 nginx worker 进程可读 - 在
http块中加载数据库:geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb { $geoip2_data_country_code source=$remote_addr country iso_code; } - 变量名
$geoip2_data_country_code是自定义的,后续可在map或if中引用 - 不要试图混用旧
geoip_country指令和geoip2,配置会直接报错
在 server 或 location 中实现地域拦截逻辑
直接在 server 或 location 块里用 if 判断 $geoip2_data_country_code 效率低且有风险(Nginx 官方不推荐在 location 中大量用 if)。更稳妥的做法是先用 map 构建布尔标记:
map $geoip2_data_country_code $allowed_country {
default 0;
CN 1;
JP 1;
KR 1;
}
然后在 server 块中:
if ($allowed_country = 0) {
return 403;
}
注意点:
-
map必须定义在http块顶层,不能嵌套在server内 -
return 403比deny all更明确,后者在某些上下文中不生效 - 测试时用
curl -x your-proxy-ip:port --header "Host: example.com" http://127.0.0.1模拟不同地区 IP,别只靠本机127.0.0.1
验证数据准确性与更新机制
GeoIP 库不是实时的——IP 归属会滞后,尤其使用代理、CDN 或移动网络时,$remote_addr 可能是 CDN 节点 IP,导致误判。若后端有真实用户 IP(如通过 X-Forwarded-For),需先用 set_real_ip_from 配置可信代理段,并启用 real_ip_header X-Forwarded-For。
数据库更新不能靠手动 cron 下载就完事:MMDB 文件被 Nginx mmap 加载后,即使文件内容变了,Nginx 也不会自动 reload 数据。必须配合 nginx -s reload 才生效(或用第三方工具如 mmdb-bin 的 mmdbctl 热更新,但非标准方案)。
真正容易被忽略的是:GeoLite2 免费版不包含城市级经纬度精度,且对 ASN、ISP 字段支持有限;商用场景务必评估数据覆盖缺口,别把 $geoip2_data_country_code == "CN" 当作“用户在中国大陆”的绝对依据。











