linux下为nginx添加geoip2地理位置解析需手动编译启用ngx_http_geoip2_module模块,配合maxmind geolite2数据库,并在配置中通过geoip2指令定义变量供日志或访问控制使用。

Linux 下为 Nginx 添加 GeoIP 地理位置解析功能,核心是编译时启用 ngx_http_geoip2_module(推荐)或旧版 ngx_http_geoip_module,并配合 MaxMind 的 GeoIP2 数据库。注意:Nginx 官方源和大多数发行版预编译包**默认不包含 GeoIP 模块**,需手动编译或使用支持该模块的第三方仓库(如 nginx.org 官方 repo 或 OpenResty)。
确认当前 Nginx 是否已支持 GeoIP2
运行以下命令检查模块是否已加载:
nginx -V 2>&1 | grep -o with-http-geoip2-module
若无输出,说明未编译进模块。也可用 nginx -V 查看完整编译参数,确认是否有 --with-http-geoip2-module。
安装依赖与 GeoIP2 数据库
先安装基础编译工具和 MaxMind 的数据库读取库:
- Ubuntu/Debian:
sudo apt update && sudo apt install build-essential libmaxminddb0 libmaxminddb-dev zlib1g-dev - CentOS/RHEL:
sudo yum install gcc make zlib-devel pcre-devel openssl-devel libmaxminddb-devel(EPEL 源需提前启用)
下载 GeoIP2 City 和 Country 数据库(免费版即可):
Zynq‑7000 / Zynq UltraScale+ 硬件调试技能。适用于 Xilinx Zynq(Cortex‑A9/A53 + FPGA)Linux 环境,调试 I2C、I2S、UART、GPIO 等外设。包括设备树配置、内核驱动、用户空间调试工具、交叉编译和常见问题排查,支持 PetaLinux 开发。
- 访问 https://www.php.cn/link/c4620e8a4aaa1f62e739608c2a866f9f
- 注册账号 → 下载
GeoLite2-Country.mmdb和GeoLite2-City.mmdb - 解压后放入统一目录,例如:
/usr/share/GeoIP/,并确保 Nginx 进程有读权限
编译安装带 GeoIP2 模块的 Nginx
若你使用的是源码安装的 Nginx,进入原 Nginx 源码目录,执行:
./configure --with-http_geoip2_module [其他原有配置项] && make && sudo make install
⚠️ 关键点:
- 务必保留原有
./configure参数(可用nginx -V查看),否则可能丢失 HTTPS、HTTP/2 等关键功能 - 若首次安装,可参考官方最小配置:
./configure --with-http_geoip2_module --with-http_ssl_module --with-http_v2_module - 编译完成后,验证:
nginx -t;重启:sudo nginx -s reload
在 Nginx 配置中启用地理位置变量
编辑 /etc/nginx/nginx.conf 或站点配置,在 http 块中添加:
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code source=$remote_addr country iso_code;
$geoip2_data_country_name source=$remote_addr country names en;
}
geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
$geoip2_data_city_name source=$remote_addr city names en;
$geoip2_data_latitude source=$remote_addr location latitude;
$geoip2_data_longitude source=$remote_addr location longitude;
}
然后在 server 或 location 块中即可使用这些变量,例如:
- 记录到日志:
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$geoip2_data_country_name" "$geoip2_data_city_name"'; - 按国家限制访问:
if ($geoip2_data_country_code != "CN") { return 403; }(注意:不建议在 location 中滥用 if,优先用 map 实现)










