nginx安装GeoIP模块,屏蔽特定地区IP

老板出国访问不了公司的系统,想起当时设置了nginx,只允许中国的IP地址访问。注释掉规则后,老板可以访问公司系统。这里写篇博客,记录一下GeoIP模块的使用。我在aws上启用了一个免费的主机,用的centos的镜像。


1.安装nginx
[root@localhost ~]# vi /etc/yum.repos.d/nginx.repo 
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=1
[root@localhost ~]# yum install nginx -y
[root@localhost ~]# service nginx start
Starting nginx:Starting nginx:                                            [  OK  ]
2.安装nginx_module_geoip
[root@localhost ~]# yum install nginx-module-geoip -y
Loaded plugins: fastestmirror, refresh-packagekit, security
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package nginx-module-geoip.x86_64 0:1.14.0-1.el6.ngx will be installed
--> Processing Dependency: GeoIP for package: nginx-module-geoip-1.14.0-1.el6.ngx.x86_64
--> Processing Dependency: libGeoIP.so.1()(64bit) for package: nginx-module-geoip-1.14.0-1.el6.ngx.x86_64
--> Finished Dependency Resolution
Error: Package: nginx-module-geoip-1.14.0-1.el6.ngx.x86_64 (nginx)
           Requires: GeoIP
Error: Package: nginx-module-geoip-1.14.0-1.el6.ngx.x86_64 (nginx)
           Requires: libGeoIP.so.1()(64bit)
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

报错,通过yum search geoip查找,发现仓库里没有安装包。

安装epel仓库,yum install epel-release -y,再次查找,仓库里有GeoIP安装包

3.下载GeoIP.dat
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz

解压后,我就放在了nginx目录下。

4.修改配置文件,使用IP筛选

为方便所有站点使用,我直接在/etc/nginx/nginx.conf中写入加载

load_module /usr/lib64/nginx/modules/ngx_http_geoip_module.so;
load_module /usr/lib64/nginx/modules/ngx_stream_geoip_module.so;
...
geoip_country /etc/nginx/GeoIP.dat;

配置单个站点使用规则,打开/etc/nginx/conf.d/default.conf

set $deny 0;
    if ($geoip_country_code != "CN"){
        set $deny 1;
        return 302 $scheme://$host/405.html;
    }
    if ($deny = 1){
        return 302 $scheme://$host/405.html;
    }

这里设置的,非中国IP不能访问。

走代理测试成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值