【Nginx 批量 IP 屏蔽】
注意,如果你用了cloudeflare域名解析,那就要注意先找到真实攻击者IP后再屏蔽,否则误杀cloudflare的IP。
====================================================
思路:先设置过滤掉Nginx白名单后的IP才是真实IP,
操作:编辑/www/server/nginx/conf/nginx.conf (宝塔常见路径,编辑主Nginx,不必要去单独设置每个网站的配置)
Nginx 获取 Cloudflare 真实 IP 的最终配置(建议写入 nginx.conf 的 http {} 块)
官方IP地址公布:https://www.cloudflare.com/zh-cn/ips/
IP一两年才更新一次。
# Cloudflare IPv4 节点
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
# Cloudflare IPv6 节点
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f248::/32;
# 设置真实 IP 获取来源头部
real_ip_header CF-Connecting-IP;
real_ip_recursive on;
注意放在nginx.conf 的 http {} 块内,重启Nginx
备注:香港8.217.11.213服务器 已经添加
通过log日志找到真实的攻击IP者后,接下来才是如果屏蔽!
如果你有几十个甚至几百个 IP 需要封锁,建议用一个外部文件:
include /etc/nginx/deny-ips.conf;
然后在 /etc/nginx/deny-ips.conf 里写所有 IP:
——————————-
deny 188.143.244.133;
deny 23.105.182.55;
deny 45.134.26.79;
...
【Nginx 少量 IP 屏蔽】
server {
listen 80;
server_name yourdomain.com;
# ===== 屏蔽多个恶意 IP =====
deny 188.143.244.133;
deny 23.105.182.55;
deny 45.134.26.79;
deny 109.237.111.11;
deny 61.177.173.50;
# ...可以继续添加更多 IP
# =========================
location / {
try_files $uri $uri/ /index.php?$args;
}
# 其他配置...
}
【直接在Linux端屏蔽】
终端输入命令封锁 IP:
iptables -A INPUT -s 188.143.244.133 -j DROP
立即生效,该 IP 所有端口的访问请求都将被丢弃(包括 HTTP、HTTPS、SSH 等)
如要查看已封锁 IP:
iptables -L -n
如需取消封锁:
iptables -D INPUT -s 188.143.244.133 -j DROP
如果你使用的是 CentOS 7/Ubuntu 20.04+,建议加一句保存规则(否则重启后失效):
CentOS:service iptables save
Ubuntu:iptables-save > /etc/iptables/rules.v4