MaxMind + GeoIP屏蔽国内IP访问网站


参考

要点

  • GeoIP2 是 MaxMind 开发的 Nginx 模块。

配置

Maxmind’s ppa

sudo add-apt-repository ppa:maxmind/ppa
apt update
apt install -y libmaxminddb0 libmaxminddb-dev mmdb-bin geoipupdate libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

配置 GeoIP

/etc/GeoIP.conf

; MaxMind 账号
AccountID 737753
LicenseKey E92xegamHTi0E4Jp
EditionIDs GeoLite2-ASN GeoLite2-City GeoLite2-Country

定时更新 geoip2

36 3    * * 2,5   root    /usr/bin/geoipupdate >> /dev/null 2>&1

下载 nginx 和 geoip2 模块源码和编译 nginx geoip 模块

# 下载机器上安装的 nginx 版本
wget http://nginx.org/download/nginx-1.16.1.tar.gz
tar zxvf nginx-1.16.1.tar.gz
wget https://github.com/leev/ngx_http_geoip2_module/archive/master.tar.gz -O ngx_http_geoip2_module.tar.gz
tar zxvf ngx_http_geoip2_module.tar.gz
cd nginx-1.16.1
./configure  --add-dynamic-module=../ngx_http_geoip2_module-master $(nginx -V) --with-compat
make

Install the new dynamic module in nginx

cp objs/ngx_http_geoip2_module.so /usr/lib/nginx/modules/
echo "load_module modules/ngx_http_geoip2_module.so;" > /etc/nginx/modules-available/mod-http-geoip2.conf
ln -s /etc/nginx/modules-available/mod-http-geoip2.conf /etc/nginx/modules-enabled/60-mod-http-geoip2.conf

配置 Nginx

修改 /etc/nginx/nginx.confdefault_type

default_type text/html;

写入 /etc/nginx/nginx.confhttp

geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
    auto_reload 60m;
    $geoip2_metadata_country_build metadata build_epoch;
    $geoip2_data_country_code country iso_code;
    $geoip2_data_country_name country names en;
}

geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
    auto_reload 60m;
    $geoip2_metadata_city_build metadata build_epoch;
    $geoip2_data_city_name city names en;
}

fastcgi_param COUNTRY_CODE $geoip2_data_country_code;
fastcgi_param COUNTRY_NAME $geoip2_data_country_name;
fastcgi_param CITY_NAME    $geoip2_data_city_name;

如何屏蔽国家

写入 /etc/nginx/nginx.confhttp

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

vhost 配置文件,写入 location / {}

if ($domain_xyz_allowed_country = no) {
                        return 444 '<!DOCTYPE html><html style="font-size:62.5%;"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"></head><body style="font:normal 100% Arial,sans-serif;font-size:14px; font-size:1.4rem;"><h1>亲爱的大陆用户:</h1><p>为了积极响应中国大陆政策号召,我不对中国大陆用户服务,感谢您的支持!</p></body></html>';
                }

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注