1. mkdir /data/geoip
2.下载安装nginx源码
wget https://nginx.org/download/nginx-1.21.0.tar.gz tar xvf nginx-1.21.0.tar.gz
3. 下载ngx_http_geoip2_module到本,并上传到/data/geoip/ngx_http_geoip2_module


4. 安装geoip数据库,需要去maxmind这个网站https://www.maxmind.com/en/accounts/1220088/geoip/downloads

解压 tar xvf GeoLite2-Country_20250829.tar.gz

5. 安装maxminddb核心库
wget https://github.com/maxmind/libmaxminddb/releases/download/1.4.2/libmaxminddb-1.4.2.tar.gz tar xvf libmaxminddb-1.4.2.tar.gz

cd libmaxminddb-1.4.2 ./configure make make check make install ldconfig sh -c "echo /usr/local/lib >> /etc/ld.so.conf.d/local.conf" ldconfig
6. cd /data/geoip/nginx-1.21.0
./configure --prefix=/etc/nginx/conf --user=root --group=root --with-threads --with-http_realip_module --with-http_ssl_module --with-stream --with-stream_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_slice_module --add-module=/data/geoip/ngx_http_geoip2_module

make -j2 mv /usr/sbin/nginx /usr/sbin/nginx_old cp -f objs/nginx /usr/sbin/
7.验证一下是否安装成功
nginx -V

可以看到安装成功了
8.修改nginx配置
vim /etc/nginx/conf/nginx.conf
# 加载 GeoLite2 数据库
geoip2 /data/GeoLite2-Country_20250829/GeoLite2-Country.mmdb {
$geoip2_data_country_code default=CN country iso_code; # 国家代码(如 CN、US)
}
include /etc/nginx/conf/conf.d/*.conf;
include /etc/nginx/conf/default.d/*.conf;
9.在具体的conf文件server块添加判断
server{
listen 80;
server_name abc.com www.abc.com;
return 301 https://$http_host$request_uri;
}
server{
listen 443;
server_name abc.com www.abc.com;
set $c $geoip2_data_country_code;
add_header "c" $c always; #添加个响应头,方便查。
location /{
set $deny 1;
if ($c = "CN"){
set $deny 0;
}
if ($deny = 1){
return 403;
}
}10.nginx -s reload重启一下,访问目的网站,查看响应头,就可以把非中国ip给屏蔽
