在日常运维工作中,会碰到这样的需求:设置网站访问只对某些ip开放,其他ip的客户端都不能访问。可以通过下面四种方法来达到这种效果:
先利用日志进行统计访问量
举例说明统计2021年13点25到14点25的日志最高访问量的前20个地址
sed -n '/2021:13:25/,/2021:14:25/p' access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -n 20
统计1分钟内访问超过100次的ip地址
#!/bin/bash
ago=`date -d "-1 min" "+%H:%M:%S"`
now=`date "+%H:%M:%S"`
sed -n "/$ago/,/$now/p" access.log | awk '{print $1}' | sort | uniq -c | sort -rn | awk '{if ($1 > 100) print $0}'
1)针对nginx域名配置所启用的端口(比如80端口)在iptables里做白名单,比如只允许100.110.15.16、100.110.15.17、100.110.15.18访问.但是这样就把nginx的所有80端口的域名访问都做了限制,范围比较大!
[root@china ~]# vim /etc/sysconfig/iptables
......
-A INPUT -s 100.110.15.16 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -s 100.110.15.17 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -s 100.110.15.18 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
2)如果只是针对nginx下的某一个域名进行访问的白名单限制,那么可以在nginx的配置文件里进行设置,利用$remote_addr参数进行访问的分发限制,如下:
[root@china vhosts]# cat testwww.wangshibo.com.conf
server {
listen 80;
server_name testwww.wangshibo.com;
root /var/www/vhosts/testwww.wangshibo.com/httpdocs/main;
access_log /var/www/vhosts/testwww.wangshibo.