安装所需依赖以及扩展
yum install libmaxminddb-devel -y
下载ngx_http_geoip2_module模块
cd /usr/local/src
git clone https://github.com/leev/ngx_http_geoip2_module.git
移动到 local 目录下
mv ngx_http_geoip2_module/ /usr/local/
ll ngx_http_geoip2_module/
查看 nginx 版本和已安装的扩展
nginx -v
nginx version: nginx/1.18.0
nginx -V
--prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-http_flv_module --with-http_mp4_module --with-openssl=../openssl-1.1.1j --with-pcre=../pcre-8.44 --with-pcre-jit --with-ld-opt=-ljemalloc
复制 在最后添加
--add-module=/usr/local/ngx_http_geoip2_module
整理后 重新 configure
./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-http_flv_module --with-http_mp4_module --with-openssl=../openssl-1.1.1j --with-pcre=../pcre-8.44 --with-pcre-jit --with-ld-opt=-ljemalloc --add-module=/usr/local/ngx_http_geoip2_module
完成后 编译
不要 make install
备份老版本nginx
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx1.16 #备份
将新编译的nginx 替换老版本 需要先 停止nginx
systemctl stop nginx
cp objs/nginx /usr/local/nginx/sbin/ #用新的去覆盖旧的
systemctl start nginx
systemctl status nginx
nginx -v
nginx -V
下载最新的IP地址数据库文件
模块安装成功后,还要在 Nginx 里指定数据库,在安装运行库时默认安装了两个,位于 /usr/share/GeoIP/ 目录下,一个只有 IPv4,一个包含 IPv4 和 IPv6:
登录 http://www.maxmind.com 网址,创建账户 下载最新的库文件(账户创建就不演示了)
点击左侧 ,Download Files
下载到本地后上传到服务器 /usr/share/GeoIP/ 目录下
cd /usr/share/GeoIP/
tar xf GeoLite2-Country_20210216.tar
cd GeoLite2-Country_20210216
cp GeoLite2-Country.mmdb ..
在 nginx.conf 配置文件内
加入
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
auto_reload 5m;
$geoip2_data_country_code country iso_code;
}
geo $allow-ip{
default no;
192.0.91.177 yes;
185.212.58.169 yes;
}
map $geoip2_data_country_code $allowed_country {
default no;
CN yes;
}
这样还不够 要想生效 还需要在 vhost 里配置
在需要屏蔽的网站配置文件内 写入
if ($allowed_country = no) {
return 403;
}
if ($allow-ip = yes ) {
set $allowed_country yes;
}
nginx -t
systemctl restart nginx
systemctl status nginx
参考链接
https://zhuanlan.zhihu.com/p/295451758
https://www.nixops.me/articles/configure-nginx-using-geoip-allow-whitelist.html