Nginx需通过ngx_http_geoip2_module模块结合GeoIP2数据库实现地理位置识别与访问控制,涉及模块编译、libmaxminddb依赖安装、.mmdb数据库加载、变量定义及基于country_code或ASN的黑白名单配置。

Nginx 本身不内置 GeoIP 功能,需依赖第三方模块(如 ngx_http_geoip2_module)结合 MaxMind 的 GeoIP2 数据库,才能精准识别访问者地理位置并实施访问控制。关键在于正确编译模块、加载数据库、配置匹配规则,并注意 IPv6 和数据更新问题。
安装 GeoIP2 模块与依赖
官方 Nginx 不含 GeoIP2 支持,需手动编译或使用预编译包:
- 推荐使用
ngx_http_geoip2_module(替代已弃用的 legacygeoip模块),它支持 GeoIP2 City/ASN 数据库和更准确的 IPv4/IPv6 解析 - 安装 libmaxminddb 开发库:
apt install libmaxminddb-dev(Ubuntu/Debian)或yum install libmaxminddb-devel(CentOS) - 下载并编译模块:克隆
https://github.com/leev/ngx_http_geoip2_module,在编译 Nginx 时添加--add-dynamic-module=/path/to/ngx_http_geoip2_module - 加载模块:在
nginx.conf的http块中加入load_module modules/ngx_http_geoip2_module.so;
配置 GeoIP2 数据库与变量
从 MaxMind 官网 下载免费版 GeoLite2 Country 或 City 数据库(.mmdb 格式),然后声明地理变量:
http {
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code country iso_code;
$geoip2_data_country_name country names en;
$geoip2_data_continent_code continent code;
}
geoip2 /usr/share/GeoIP/GeoLite2-ASN.mmdb {
$geoip2_asn_number autonomous_system_number;
$geoip2_asn_org autonomous_system_organization;
}
}
注意路径权限需让 nginx worker 进程可读;变量名可自定义,但必须以 $ 开头且唯一。
基于地理位置限制访问
利用上述变量,在 server 或 location 块中配合 if + deny/return 实现黑白名单控制:
- 禁止特定国家访问:
if ($geoip2_data_country_code = "CN") { return 403; } - 仅允许部分国家访问:
if ($geoip2_data_country_code !~ ^(US|JP|DE)$) { return 403; } - 结合 ASN 限制数据中心流量:
if ($geoip2_asn_number >= 10000 && $geoip2_asn_number - 注意:
if在 location 中慎用,建议将规则放在server级或用map提前计算布尔值,避免重复执行
验证与维护要点
配置完成后务必测试有效性:
- 用 curl 模拟不同地区 IP(如通过代理或 Cloudflare 的
CF-Connecting-IP头)检查响应状态码 - 启用
error_log调试级别查看 geoip2 加载是否成功,常见错误包括文件路径错、权限不足、mmdb 版本不兼容 - GeoLite2 数据库需定期更新(MaxMind 提供每周自动下载脚本),建议用 cron 定期替换并重载 Nginx:
nginx -s reload - 若使用 CDN(如 Cloudflare),需确保真实客户端 IP 传递到 Nginx(设置
real_ip_header CF-Connecting-IP;并配置set_real_ip_from)


















