Ubuntu下Nginx配置GeoIP限制国外访问

假设你已经对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/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值