需重新编译Nginx并添加--with-http_geoip_module:先确认当前版本与依赖库,下载同版本源码,复用原configure参数追加该模块,make后替换二进制,再配置geoip_country及map规则实现地域访问控制。

在 Linux 下为已安装的 Nginx 源码编译添加 GeoIP 模块,需要重新编译 Nginx 并启用 --with-http_geoip_module(注意:该模块在 Nginx 1.11.3+ 已被弃用,推荐使用 ngx_http_geoip2_module;但若系统仍用旧版或需兼容,以下以传统 GeoIP 为例说明)。
确认当前 Nginx 是否支持 GeoIP 及依赖环境
执行 nginx -V 查看编译参数,确认输出中是否含 --with-http_geoip_module。若无,则需重编译。同时检查是否已安装 GeoIP 库:
- CentOS/RHEL:
yum install geoip-devel - Ubuntu/Debian:
apt-get install libgeoip-dev - 验证库存在:
ls /usr/lib64/libGeoIP.so或/usr/lib/libGeoIP.so
下载并解压对应版本的 Nginx 源码
必须使用与当前运行 Nginx 完全相同版本号 的源码,否则配置、二进制不兼容。例如当前是 nginx version: nginx/1.18.0,则去 nginx.org/download/ 下载 nginx-1.18.0.tar.gz,然后解压:
tar zxvf nginx-1.18.0.tar.gzcd nginx-1.18.0
配置并重新编译 Nginx
复用原编译参数,在末尾追加 --with-http_geoip_module。可从 nginx -V 输出中复制 configure arguments(去掉 configure arguments: 前缀),例如:
./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx \ --modules-path=/usr/lib64/nginx/modules \ --conf-path=/etc/nginx/nginx.conf \ --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log \ --pid-path=/var/run/nginx.pid \ --lock-path=/var/run/nginx.lock \ --http-client-body-temp-path=/var/cache/nginx/client_temp \ --http-proxy-temp-path=/var/cache/nginx/proxy_temp \ --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \ --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \ --http-scgi-temp-path=/var/cache/nginx/scgi_temp \ --user=nginx --group=nginx \ --with-compat --with-file-aio --with-threads \ --with-http_addition_module --with-http_auth_request_module \ --with-http_dav_module --with-http_flv_module \ --with-http_gunzip_module --with-http_gzip_static_module \ --with-http_mp4_module --with-http_random_index_module \ --with-http_realip_module --with-http_secure_link_module \ --with-http_slice_module --with-http_ssl_module \ --with-http_stub_status_module --with-http_sub_module \ --with-http_v2_module --with-mail --with-mail_ssl_module \ --with-stream --with-stream_realip_module \ --with-stream_ssl_module --with-stream_ssl_preread_module \ --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions' \ --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' \ --with-http_geoip_module
之后执行:
-
make(不运行make install,避免覆盖配置) - 备份原二进制:
cp /usr/sbin/nginx /usr/sbin/nginx.bak - 替换二进制:
cp objs/nginx /usr/sbin/nginx - 验证:
nginx -t确保配置正常,nginx -V 2>&1 | grep geoip应有输出
配置 GeoIP 模块并测试
编辑 /etc/nginx/nginx.conf 或站点配置,在 http 块中添加:
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
CN yes;
US yes;
}
在 server 块中使用,例如限制仅允许中国和美国访问:
if ($allowed_country = no) {
return 403;
}
注意:/usr/share/GeoIP/GeoIP.dat 需存在,可通过 yum install geoip-update 或手动下载更新。重启 Nginx 后即可生效。


















