加载 ngx_http_geoip 模块需要在编译 nginx 时通过 --with-http_geoip_module 参数启用,并在配置文件中调用 geoip_country 或 geoip_city 指令。该模块依赖 maxmind 的 geoip 数据库文件,因此必须确保系统已安装 libmaxminddb 库。编译完成后,nginx 进程启动时会读取指定的 .mmdb 文件并建立内存映射,从而实现基于客户端 ip 的地理位置识别。

如何编译包含 geoip 模块的 Nginx
编译时必须指定 --with-http_geoip_module 选项,否则生成的二进制文件将不包含该模块的功能。同时需要链接 libmaxminddb 库以支持新版 GeoLite2 数据库格式。如果使用的是旧版 GeoIP 数据库(.dat),则需要链接 libgeoip 库。以下是一个标准的编译流程示例,假设源码位于 /usr/local/src/nginx-1.24.0。
cd /usr/local/src/nginx-1.24.0
./configure \
--prefix=/etc/nginx \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--pid-path=/run/nginx.pid \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_geoip_module \
--with-libmaxminddb=/usr/local/libmaxminddb \
make
sudo make install执行上述命令后,nginx -V 的输出中应包含 --with-http_geoip_module 字样,确认模块已成功嵌入。若未找到 libmaxminddb,需先编译安装该库或使用包管理器安装开发包(如 libmaxminddb-dev)。
如何在 Nginx 配置中使用 geoip 变量
在 nginx.conf 的主上下文或 server 块中,使用 geoip_country 指令加载国家代码数据库,并使用 geoip_city 指令加载城市数据库。这些指令会定义一系列全局变量,如 $geoip_country_code、$geoip_city_country_name 等,供后续逻辑判断或日志记录使用。例如,可以根据国家代码限制访问或重定向到特定语言页面。
geoip_country /usr/share/GeoIP/GeoLite2-Country.mmdb;
geoip_city /usr/share/GeoIP/GeoLite2-City.mmdb;
server {
listen 80;
server_name example.com;
location / {
# 根据国家代码设置默认语言
if ($geoip_country_code = CN) {
rewrite ^ http://cn.example.com$request_uri permanent;
}
# 记录城市信息到日志
access_log /var/log/nginx/access.log combined;
}
}配置生效后,Nginx 会在每次请求处理时查询内存中的数据库,返回对应的地理位置信息。注意数据库文件路径必须是 Nginx 工作用户(通常是 www-data 或 nginx)可读的绝对路径。若文件权限不足,Nginx 将在错误日志中报错并拒绝加载模块。
Nginx 配置与调优技能。支持反向代理、负载均衡、SSL/TLS 终止、高性能静态资源服务。触发词:Nginx 配置、代理设置、SSL 证书、性能调优、负载均衡、反向代理。

geoip 模块如何处理 IPv6 地址查找
当客户端使用 IPv6 地址连接时,ngx_http_geoip 模块会自动尝试在 IPv6 专用的数据库文件中查找匹配项。如果仅加载了 IPv4 数据库(如 GeoLite2-Country.mmdb),IPv6 请求将无法匹配任何记录,相关变量(如 $geoip_country_code)将为空字符串。为了支持 IPv6,必须额外加载 IPv6 数据库文件,并通过 geoip_country 和 geoip_city 指令分别指定 IPv4 和 IPv6 的数据源。
geoip_country /usr/share/GeoIP/GeoLite2-Country.mmdb; geoip_country /usr/share/GeoIP/GeoLite2-Country-IPv6.mmdb ipv6; geoip_city /usr/share/GeoIP/GeoLite2-City.mmdb; geoip_city /usr/share/GeoIP/GeoLite2-City-IPv6.mmdb ipv6;
在上述配置中,第二个 geoip_country 指令带有 ipv6 参数,明确指示 Nginx 使用指定的 IPv6 数据库。这种双数据库机制确保了 IPv4 和 IPv6 流量都能获得准确的地理位置数据。若未正确配置 IPv6 数据库,IPv6 用户的访问将被视为未知地区,可能导致基于地域的策略失效。


















