大螃嗨

好记性不如烂笔头

用户工具

站点工具


nginx_ip访问限制

IP国家访问限制

需求:

通过nginx GeoIP模块来限制某些国家或者具体地区访问网站。

先看nginx有没有编译geoip模块,如果有就直接修改就行,没有就得先安装。

nginx -V #查看目前的nginx相关配置

已经安装过

0: 查看nginx的配置文件位置

$ nginx -t

1:修改nginx.conf的http区域,在里面加上这段

geoip_country /usr/share/GeoIP/GeoIP.dat;   #GeoIP所在目录
map $geoip_country_code $allowed_country {  #变量判断
default yes;   #允许
CN no;  #区域不允许,这个CN就是代表中国,如果是多个地区,就是CN下面加就行
}

2:修改nginx.conf的server区域

location / {
root /data/wwwroot/test;  #网站目录
if ($allowed_country = no) {  #这里的no,就是上面html里面CN on,就是判断no区域
 
#if ($allowed_country = no) 也可以用if ($geoip_country_code = CN) 来代替,如果是多个区域就在CN后面几个|然后加区域代码
#以下3中方式选择一种
return 403;   #返回403提示
return http://域名; #跳转到其他人网站去 ,return也可以用rewrite,具体看自己网站的配置文件怎么设置的
root /data/wwwroot/test1;  #跳转到自己服务器的另外一个文件夹下面去
}
}

3: 重启nginx

$ nginx -t
$ nginx -s reload

Geoip模块的安装方法

yum -y install geoip-devel  #CentOS系统
 
#这会自动安装到/usr/share/GeoIP文件夹下,这个安装的并不一定是最新的,我们就更新下
 
mv /usr/share/GeoIP/GeoIP.dat /usr/share/GeoIP/GeoIP.dat_bak   #备份下
 
cd /usr/share/GeoIP  #进文件夹
 
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz  #下载最新数据库
 
gunzip GeoIP.dat.gz  #解压出来
 
cd /root/oneinstack/src/nginx-1.12.1  #进入当前nginx文件夹  根据自己目录来
 
./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-http_v2_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-http_flv_module --with-http_mp4_module --with-openssl=../openssl-1.0.2l --with-pcre=../pcre-8.41 --with-pcre-jit --with-ld-opt=-ljemalloc --add-module=../lua-nginx-module --add-module=../ngx_devel_kit --with-http_geoip_module  #添加编译模块
 
就是把--with-http_geoip_module加到原来的编译上去
 
make && make install  #执行编译
nginx_ip访问限制.txt · 最后更改: 2019/07/07 17:35 由 螃蟹