限制某个国家访问或者只允许某个国家访问我们的服务,有两种做法,一种是在Ningx里面限制,一种是在程序里面限制;程序里面下载GeoLite2-Country.mmdb库,实现很简单。今天主要讲 nginx中如何实现


安装libmaxminddb

1
yum install libmaxminddb-devel -y

安装Nginx模块

1
git clone https://github.com/leev/ngx_http_geoip2_module.git

重新编译nginx

通过nginx -V查看nginx原来编译参数

1
2
3
./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-http_sub_module --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-openssl=/opt/lnmp1.9/src/openssl-1.1.1o --with-openssl-opt='enable-weak-ssl-ciphers' --add-module=/usr/local/ngx_http_geoip2_module

make && make install

下载GeoLite2-Country.mmdb文件

GeoLite2 Free Geolocation Data | MaxMind Developer Portal

nginx 配置

不允许中国访问

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
geoip2 /opt/GeoLite2-Country.mmdb {
  auto_reload 5m;
  $geoip2_data_country_code country iso_code;
}

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

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