nginx默认不内置geoip模块,需编译时启用:推荐geoip2(需libmaxminddb及ngx_http_geoip2_module静态编译),旧版geoip仅兼容遗留场景且nginx 1.13.7+已移除;安装后需下载.mmdb数据库并配置geoip2指令使用。

Nginx 默认不内置 GeoIP 模块,需在编译时显式启用。注意:GeoIP 有 GeoIP(Legacy) 和 GeoIP2 两种,前者已停止维护,推荐使用 GeoIP2;但两者编译方式不同,下面分情况说明。
一、编译安装支持 GeoIP2(推荐)
GeoIP2 使用 MaxMind 的新格式(.mmdb),功能更全、更新及时,需配合 ngx_http_geoip2_module 模块。
- 提前安装依赖:
libmaxminddb(C 库)和mmdblookup(可选,用于调试) - Ubuntu/Debian:
sudo apt install libmaxminddb-dev libmaxminddb0 - CentOS/RHEL:
sudo yum install libmaxminddb-devel(EPEL 源需启用) - 下载并解压 Nginx 源码(如 nginx-1.24.0)
- 克隆 GeoIP2 模块:
git clone https://github.com/leev/ngx_http_geoip2_module.git - 进入 Nginx 源码目录,执行 configure(关键参数):
./configure --add-module=../ngx_http_geoip2_module \<br> --with-http_ssl_module --with-http_v2_module
(其他模块按需添加,--add-module必须指向模块源码路径) - 执行
make && sudo make install
二、编译安装支持旧版 GeoIP(仅兼容遗留场景)
该模块基于已停更的 GeoIP Legacy(.dat 文件),仅适用于老系统或特定需求。
- 安装
libgeoip1开发包:
Ubuntu/Debian:sudo apt install libgeoip-dev
CentOS/RHEL:sudo yum install geoip-devel - configure 时添加:
--with-http_geoip_module(无需额外 add-module,是 Nginx 官方内置模块,但默认不启用) - 注意:Nginx 1.13.7+ 已移除此模块,如需使用必须降级或打补丁,不建议新项目采用
三、验证与基础配置
安装完成后检查是否生效:
- 运行
nginx -V 2>&1 | grep -o with-http_geoip(旧版)或grep -o geoip2(新版),确认输出含对应关键词 - 下载 MaxMind 免费数据库:GeoLite2 City(.mmdb 格式),放到如
/usr/share/GeoIP/GeoLite2-City.mmdb - Nginx 配置示例(GeoIP2):
http {<br> geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {<br> $geoip2_data_country_code source=$remote_addr country iso_code;<br> $geoip2_data_city_name source=$remote_addr city name;<br> }<br><br> server {<br> location / {<br> add_header X-Country $geoip2_data_country_code;<br> add_header X-City $geoip2_data_city_name;<br> }<br> }<br>}
四、常见问题提醒
- 数据库路径必须可读,且 Nginx worker 进程有权限访问(避免 SELinux 或文件权限拦截)
- GeoIP2 模块不支持动态加载(.so),必须静态编译进主程序
- 若用 OpenResty,它已内置
resty-maxminddb,无需重新编译 Nginx,可直接用 Lua 调用 - 线上环境建议定期更新 .mmdb 文件(MaxMind 每月发布新版本)











