用nginx的geoip/geoip2模块来限制地区的访问;
1、安装相应地区地址模块库相应的包
yum install libmaxminddb libmaxminddb-devel -y
数据库地址:
http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz
http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz
我这是放在 /usr/local/share/GeoIP/ 里面。
2、检查nginx是否已经安装ngx_http_geoip2_module模块
nginx -V
3、如果没有安装,重新编译安装nginx的ngx_http_geoip2_module
git clone https://github.com/leev/ngx_http_geoip2_module
tar -xf nginx-1.10.1.tar.gz
cd nginx-1.10.1
./configure --prefix=/home/deploy/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --add-dynamic-module=/home/deploy/nginx/ngx_http_geoip2_module
make && make install
4、nginx配置文件规则设置
http段进行国家代码的map映射:
geoip2 /usr/local/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_data_country_code country iso_code;
}
map $geoip2_data_country_code $allowed_country {
default no;
CN yes;
}
站点的server段里面加一下拒绝:
if ($allowed_country = no) {
return 403;
}
最后重启一下nginx就行了。
我这的规则是默认拒绝,只允许中国,可以根据情况调整。