caijinlin
6/12/2018 - 3:14 AM

Nginx屏蔽IP访问

Nginx屏蔽IP访问

屏蔽访问过于频繁的IP,编写脚本需要根据实际的nginx服务器log日志,取出访问IP和User-Agent,在nginx配置nginx.conf文件中添加内容:
```shell
include ./vhost/blocksip.conf;
```

编写脚本内容:blocksip.sh 
```bash
#!/bin/bash
nginx_home=/usr/local/nginx
log_path=/usr/local/nginx/logs
tail -n50000 /usr/local/nginx/logs/access.log \
|awk '{print $1,$12}' \
|grep -i -v -E "google|baidu|qq|so|sogou" \
|awk '{print $1}'|sort|uniq -c|sort -rn \
|awk '{if($1>1000)print "deny "$2";"}' >$nginx_home/conf/vhost/blocksip.conf
/usr/local/nginx/sbin/nginx -s reload
```

nginx允许和禁止某个IP或IP段的访问都建立在该访问可以正常通过iptable防火墙。当然,也可以把过滤出的ip直接加到iptables中,彻底拒绝该ip的所有请求。

参考 https://blog.yoodb.com/yoodb/article/detail/1332