假设你已经对Nginx有所了解,想要通过GeoIP来限制地区访问。
1,查看是否安装GeoIP module
nginx -V
会列出所有安装的模块,新版本的nginx默认都是用的,没有的话自己安装
2,下载GeoIP数据库
通过如下命令下载的方式已经行不通了
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
这里建议下载这个:
链接:https://pan.baidu.com/s/1oQ3nZijIoGGd6Ph_zBhgmQ
提取码:7w18
3,配置Nginx
vi /etc/nginx/nginx.conf
添加geoip_country (geoip_city)到http{}范围内
[...]
http {
##
# Basic Settings
##
geoip_country /etc/nginx/geoip/GeoIP.dat; # the country IP database
geoip_city /etc/nginx/geoip/GeoLiteCity.dat; # the city IP database
[...]
geoip_country
指令包含如下可用参数
$geoip_country_code - two-letter country code, for example, RU, US.
$geoip_country_code3 - three-letter country code, for example, RUS, USA.
$geoip_country_name - the (verbose) name of the country, for example, Russian Federation, United States, etc.
geoip_city
指令包含如下可用参数:
$geoip_city_country_code - two-letter country code, for example, RU, US.
$geoip_city_country_code3 - three-letter country code, for example, RUS, USA.
$geoip_city_country_name - the name of the country, for example, Russian Federation, United States - if available.
$geoip_region - the name of region (province, region, state, province, federal land, and the like), for example, Moscow City, DC - if available.
$geoip_city - the name of the city, for example, Moscow, Washington, Lisbon, etc. - if available.
$geoip_postal_code - zip code or postal code - if available.
$geoip_city_continent_code - if available.
$geoip_latitude - latitude - if available.
$geoip_longitude - longitude - if available.
4,配置sites_avaiable
[...]
location / {
# index index.html index.php;
# try_files /index_$geoip_country_code.html /index.html;
if ($geoip_country_code != CN) {// 访问者来自国外,返回404
return 404;
}
}
[...]
注意:nginx配置中if后面必须要有空格,如下:
// 可行
if ($geoip_country_code != CN){
}
// 不行
if($geoip_country_code != CN){
}
5,重启
nginx -s reload
参考:
https://blog.csdn.net/palet/article/details/103394236
https://www.howtoforge.com/tutorial/how-to-use-geoip-with-nginx-on-ubuntu-16.04/