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

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


1.安装nginx
[[email protected] ~]# vi /etc/yum.repos.d/nginx.repo 
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=1
[[email protected] ~]# yum install nginx -y
[[email protected] ~]# service nginx start
Starting nginx:Starting nginx:                                            [  OK  ]
2.安装nginx_module_geoip
[[email protected] ~]# 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不能访问。

走代理测试成功。

文章来源: nginx安装GeoIP模块,屏蔽特定地区IP

人吐槽 人点赞

猜你喜欢

发表评论

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:nginx安装GeoIP模块,屏蔽特定地区IP