15. Nginx Geo

新方法

  • 安装 nginx 模块 geoip2: https://github.com/leev/ngx_http_geoip2_module
  • 下载 IP 识别数据源:https://www.maxmind.com/en/accounts/262101/geoip/downloads,需要注册网站账号才有权限下载,下载的数据库选择 GeoLite2 CityGeoLite2 Country 即可
  • nginx 配置如下,source 选项对应的是 $remote_addr, 表示解析的是用户IP,可以修改为其他变量
http {
    ...
     geoip2 /etc/nginx/vendor/GeoLite2-Country.mmdb {
        auto_reload 5m;
        $geoip2_metadata_country_build metadata build_epoch;
        $geoip2_data_country_code default=US source=$remote_addr country iso_code;
        $geoip2_data_country_name country names en;
    }

    geoip2 /etc/nginx/vendor/GeoLite2-City.mmdb {
        $geoip2_data_city_name default=London 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;
    ....
    
    server {
        listen 8081;
        server_name www.siguoya.name;
        location / {
            if ($geoip2_data_country_code != 'CN'){
                return 403;
            }
            default_type text/plain;
            return 200 "$remote_addr $geoip2_data_country_code $geoip2_data_country_name $geoip2_data_city_name";
       }
   }
}

访问:http://www.siguoya.name:8081/

113.111.3.206 CN China Guangzhou

旧方法

由于 maxmind 不再提供 dat 格式的数据下载以及维护,以下方法已废弃

IP数据库下载地址:
国家数据库:http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
城市数据库:http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

http {
  geoip_country /path/to/GeoIP.dat;
  geoip_city /path/to/GeoLiteCity.dat;
  server{
    listen 3592;
    location / {
      default_type text/plain;
      if ($geoip_country_code != 'CN'){
        return 403;
      }
      return 200 "$remote_addr $geoip_city_country_name $geoip_country_code $geoip_city";
    }
  }
}

访问:http://www.siguoya.name:3592/

119.32.216.122 China CN Guangzhou

专题阅读

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值