nginx 拦截境外访问
编译geoip2_module 安装模块
以容器案例
cat dockerfile
FROM nginx:1.24.0
RUN apt-get update && apt-get install -y libmaxminddb0 libmaxminddb-dev mmdb-bin git gcc make libpcre3-dev zlib1g-dev wget --no-install-recommends && rm -rf /var/lib/apt/lists/*
WORKDIR /usr/src
RUN wget https://nginx.org/download/nginx-1.24.0.tar.gz && tar -zxf nginx-1.24.0.tar.gz
RUN git clone https://github.com/leev/ngx_http_geoip2_module.git
WORKDIR /usr/src/nginx-1.24.0
RUN ./configure --with-compat --add-dynamic-module=../ngx_http_geoip2_module
RUN make modules && cp objs/ngx_http_geoip2_module.so /etc/nginx/modules/
RUN mkdir -p /usr/share/GeoIP
RUN wget -O /usr/share/GeoIP/GeoLite2-Country.mmdb https://git.io/GeoLite2-Country.mmdb
RUN wget -O /usr/share/GeoIP/GeoLite2-City.mmdb https://git.io/GeoLite2-City.mmdb
nginx 主配置 最顶添加 load_module modules/ngx_http_geoip2_module.so;
http{}模块添加
geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
$geoip2_country_code country iso_code;
}
map $geoip2_country_code $allow_access {
default 0;
CN 1;
HK 0; # 香港
TW 1; # 台湾
MO 1; # 澳门
}
geo $is_lan {
default 0;
172.16.0.0/24 1;
10.8.10.0/24 1;
127.0.0.0/8 1;
}
map "$is_lan:$allow_access" $final_deny {
default 1;
"1:0" 0; # 内网放行
"0:1" 0; # 允许的国家
}
server {} 添加限制
if ($final_deny = 1) {
return 403 '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"></head><body><h1 style="font-size:36px;color:red;font-weight:bold;">非法访问</h1></body></html>';
}

浙公网安备 33010602011771号