1. mkdir /data/geoip

2.下载安装nginx源码

Markup

wget https://nginx.org/download/nginx-1.21.0.tar.gz
tar xvf nginx-1.21.0.tar.gz
  1. 下载ngx_http_geoip2_module到本,并上传到/data/geoip/ngx_http_geoip2_module

image.png

image.png

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

image.png

解压 tar xvf GeoLite2-Country_20250829.tar.gz

image.png

  1. 安装maxminddb核心库

Markup

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

image.png

Markup

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
  1. cd /data/geoip/nginx-1.21.0

Markup

./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

image.png

Markup

make -j2
mv /usr/sbin/nginx  /usr/sbin/nginx_old
cp -f objs/nginx /usr/sbin/

7.验证一下是否安装成功

nginx -V

image.png

可以看到安装成功了

8.修改nginx配置

vim /etc/nginx/conf/nginx.conf

Markup

# 加载 GeoLite2 数据库
    geoip2 /data/GeoLite2-Country_20250829/GeoLite2-Country.mmdb {
        $geoip2_data_country_code default=CN country iso_code;  # 国家代码(如 CN、US)
    }

image.png

include /etc/nginx/conf/conf.d/*.conf;

include /etc/nginx/conf/default.d/*.conf;

9.在具体的conf文件server块添加判断

Markup

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给屏蔽

image.png