自学nginx(四): 禁止从某国家的访问

下载ngx_http_geoip_module.so

由于nginx安装的时候,geoip模块是dynamic。用nginx -V可以看到。
所以需要另外下载so文件。

sudo yum install nginx-mod-http-geoip

执行完成后会在/usr/lib64/nginx/modules/ngx_http_geoip_module.so有这个文件。
并且/usr/share/nginx/modules/mod-http-geoip.conf 这个文件也多了出来。所以geoip的模块会自动被nginx.conf加载。

下载geoip文件

在这里可以下载到GeoIP.dat和GeoLiteCity.dat文件。
https://dev.maxmind.com/geoip/legacy/geolite/
可以将这两个文件放到/usr/share/GeoIP/下

编写geoip.conf文件

在/etc/nginx/conf.d/下,编写geoip.conf文件如下:

geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;

编写nginx.conf文件

可以把$geoip_country_code, $geoip_city加入到access_log中。此步骤可选。看你自己的需求。

反向代理的话,可以设置一些变量到header中传下去。此步骤可选。看你自己的需求。

proxy_set_header GEOIP_COUNTRY_CODE $geoip_country_code;
proxy_set_header GEOIP_COUNTRY_CODE3 $geoip_country_code3;
proxy_set_header GEOIP_COUNTRY_NAME $geoip_country_name;

proxy_set_header GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;
proxy_set_header GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3;
proxy_set_header GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name;
proxy_set_header GEOIP_REGION $geoip_region;
proxy_set_header GEOIP_CITY $geoip_city;
proxy_set_header GEOIP_POSTAL_CODE $geoip_postal_code;
proxy_set_header GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code;
proxy_set_header GEOIP_LATITUDE $geoip_latitude;
proxy_set_header GEOIP_LONGITUDE $geoip_longitude;
写一个map定义规则
map $geoip_country_code $allowed_country {
        default yes; # default都能访问
        US no; # 禁止从美国的访问
}
在server中应用map规则
server {
        ...其他部分省略...

        if ($allowed_country = no) {
            # 444是空response
            return 444;
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值