在Nginx中需通过源码编译启用官方内置的ngx_http_geoip_module模块,前提是系统已安装libgeoip开发库,并在configure时添加--with-http_geoip_module参数,再配置geoip_country等指令加载GeoIP.dat数据库。

在 Nginx 中通过源码编译安装 GeoIP(注意:不是 GeoIP2)地理定位模块,需要手动下载并链接 libgeoip 库,再将 ngx_http_geoip_module 编译进 Nginx。该模块是 Nginx 官方内置模块(从 1.3.8 开始默认启用),但需满足依赖条件且不能通过包管理器直接启用——必须源码编译。
确认系统已安装 GeoIP 库开发文件
GeoIP 模块依赖系统级的 libgeoip 动态库和头文件。不同系统安装方式略有差异:
-
Ubuntu/Debian:
sudo apt install libgeoip-dev -
CentOS/RHEL 7/8:
sudo yum install geoip-devel(RHEL 8 可能需启用PowerTools或使用dnf install GeoIP-devel) -
macOS(Homebrew):
brew install geoip
安装后检查关键路径是否存在:/usr/include/GeoIP.h 和 /usr/lib/libGeoIP.so(或 /usr/lib64/ 下)。若路径不同(如自定义安装),后续需用 --with-cc-opt 和 --with-ld-opt 显式指定。
下载并解压 Nginx 源码
前往 nginx.org 官网 下载稳定版源码(例如 nginx-1.24.0.tar.gz),解压后进入目录:
tar -zxvf nginx-1.24.0.tar.gz<br>cd nginx-1.24.0
无需额外下载模块代码——ngx_http_geoip_module 已包含在 Nginx 源码的 src/http/modules/ngx_http_geoip_module.c 中,只要启用即可。
配置编译参数并启用 GeoIP 模块
执行 ./configure 时添加 --with-http_geoip_module 参数。典型命令如下:
./configure \<br> --prefix=/usr/local/nginx \<br> --with-http_geoip_module \<br> --with-http_ssl_module \<br> --with-http_v2_module
如果 libGeoIP 安装在非标准路径(如 /opt/geoip),需补充:
--with-cc-opt="-I/opt/geoip/include" \<br>--with-ld-opt="-L/opt/geoip/lib -lGeoIP"
运行 make && sudo make install 完成安装。验证是否成功:
/usr/local/nginx/sbin/nginx -V 2>&1 | grep -o with-http_geoip-module
有输出即表示模块已编译进内核。
配置 Nginx 使用 GeoIP 变量
编辑 nginx.conf,在 http 块中加载 GeoIP 数据库并定义变量:
http {<br> geoip_country /usr/share/GeoIP/GeoIP.dat;<br> geoip_city /usr/share/GeoIP/GeoIPCity.dat;<br><br> # 可选:映射为更易读的变量<br> map $geoip_country_code $country_name {<br> default "Unknown";<br> CN "China";<br> US "United States";<br> }<br><br> server {<br> location / {<br> add_header X-Country $geoip_country_name;<br> add_header X-City $geoip_city;<br> }<br> }<br>}注意:GeoIP.dat 和 GeoIPCity.dat 需提前下载(可从 MaxMind Legacy 页面 获取免费版),并确保 Nginx 有读取权限。重启 Nginx 后即可通过请求头或日志查看地理位置信息。











