在 Linux 下使用 Nginx 禁止某个 IP 或 IP 段访问,常见做法如下:
编辑 Nginx 配置文件(如 nginx.conf 或站点配置 /etc/nginx/conf.d/xxx.conf):
server {
listen 80;
server_name example.com;
# 禁止 1.2.3.4 访问
deny 1.2.3.4;
allow all;
}
✅ deny 写在前面,allow all 放最后
✅ 支持 IPv4 / IPv6
deny 1.2.3.4;
deny 5.6.7.8;
allow all;
deny 192.168.1.0/24;
allow all;
location 中限制(更精细)location /admin/ {
deny 1.2.3.4;
allow all;
}
include 统一管理黑名单(推荐)vim /etc/nginx/blockips.conf
内容:
deny 1.2.3.4;
deny 192.168.0.0/16;
include /etc/nginx/blockips.conf;
allow 10.0.0.1;
allow 127.0.0.1;
deny all;
nginx -t
systemctl reload nginx
iptables -A INPUT -s 1.2.3.4 -j DROP
或修改 /etc/hosts.deny
如果你需要:
可以告诉我你的使用场景,我可以给你更合适的方案。