Nginx 禁止国外ip访问(debian版本)

  1. 参考下面脚本安装 Nginx
#!/bin/bash
## install nginx
WORK_DIR=`mktemp -d`
apt install wget libpcre3 libpcre3-dev zlib1g-dev \
    openssl libssl-dev libxml2 libxml2-dev libxslt-dev  \
    gcc  make libgd-dev  libgeoip-dev  libperl-dev libmaxminddb* 
cd /opt && git clone https://github.com/leev/ngx_http_geoip2_module.git

cd $WORK_DIR
wget http://nginx.org/download/nginx-1.20.1.tar.gz

tar zxvf nginx-1.20.1.tar.gz && cd nginx-1.20.1
./configure --prefix=/opt/nginx --user=apache --group=apache \
    --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module \
    --with-pcre --with-http_v2_module --with-http_dav_module \
    --with-http_flv_module --with-http_realip_module --with-http_addition_module \
    --with-http_xslt_module --with-http_sub_module --with-http_random_index_module \
    --with-http_degradation_module --with-http_secure_link_module --with-http_perl_module \
    --add-module=/opt/ngx_http_geoip2_module \
    --with-debug --with-file-aio --with-stream --with-ld-opt=-Wl,-E
make && make install
cd ~ && [ -d $WORK_DIR ] && rm $WORK_DIR -rf

## 添加nginx运行账户
cat /etc/passwd | grep apache
if [ $? -ne 0 ];then
    groupadd apache
    useradd -g apache -s /sbin/nologin -c "apache" apache
fi
  1. 下面一个示例的 nginx 配置文件
user  apache;
worker_processes  auto;

events {
    worker_connections  65535;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    tcp_nopush     on;
    keepalive_timeout  65;
    gzip  on;

    #  GeoLite2-Country.mmdb 这个文件需要到 'https://dev.maxmind.com' 自行下载并放到 ' /usr/share/GeoIP' 这个目录下
    geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
        auto_reload 5m;
        $geoip2_data_country_code country iso_code;
    }

    map $geoip2_data_country_code $allowed_country {
        default yes;
        CN no;
    }

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        if ($allowed_country = yes) {
            return 403;
        }
    }

}

  1. 测试的话需要用一个国外的节点进行测试