![](https://img-blog.csdnimg.cn/img_convert/6e9b14f7a66a1f2b473efdcec67da2c8.webp?x-oss-process=image/format,png)
###### 4)还可以利用nginx的allow、deny参数进行访问限制
##白名单设置,只允许下面三个来源ip的客户端以及本地能访问该站。
allow 100.110.15.16;
allow 100.110.15.17;
allow 100.110.15.18;
allow 127.0.0.1;
deny all;
![](https://img-blog.csdnimg.cn/img_convert/4685ffa2808863df7c578de8e892e3e3.webp?x-oss-process=image/format,png)
三、Nginx根据用户IP设置访问跳转
**第一种方法**
根据$remote\_addr客户端IP地址判断,判断成功即返回301跳转,可以写正则,如果有大量不规则IP就很头疼了。
if ($remote_addr = 192.168.1.123) {
return 301 https://blog.whsir.com;
}
**第二种方法**
nginx通过lua实现,这方法是[孔大神]( )给的,将需要做301跳转的IP,直接写到/tmp/ip文件中,支持网段,一行一个,添加后不需要重启nginx,即时生效。
注意nginx要[编译lua模块]( )才可以使用,我的[whsir一键包]( )nginx已集成lua。
rpm -ivh http://mirrors.whsir.com/centos/whsir-release-centos.noarch.rpm
yum install wnginx -y
set_by_lua $info ’
local opt = ngx.var.remote_addr
local file = io.popen(“ip=” …opt… “;if grep -q $ip /tmp/ip;then echo $ip; exit 0;fi ; for net in $(grep / /tmp/ip);do [ $(ipcalc -n i p / ip/ ip/{net#*/}) = $(ipcalc -n $net) ] && echo $ip && break; done”)
content1 = file:read(“*l”)
return content1
';
if ( $info = $remote_addr) {
return 301 https://blog.whsir.com;
}
##### 四、nginx配置IP白名单的详细步骤
分析nginx访问日志,有哪些IP访问过nginx。
命令参考:
awk ‘{print $1}’ logs/access.log | sort | uniq -c | sort -nr -k1
输出的效果案例:
1053 192.168.3.15
893 192.168.3.10
818 192.168.0.8
###### 1、添加IP白名单文件
在nginx目录的 conf 中添加文件 ip.conf,注意白名单文件不用添加任何注释,可以有空行
vi ip.conf
192.168.3.11 1;
192.168.3.10 1;
192.168.0.112 1;
2、配置nginx.conf
编辑http节点:
http {
# …
# geo IP whitelist
geo $remote_addr $ip_whitelist {
default 0;
include ip.conf;
}
# …
}
编辑server节点:
server {
listen 80;
# …
# IP whitelist
set $whitelist_flag 1;
if ( $ip_whitelist != 1 ) {
set w h i t e l i s t f l a g