Hugo博客公告弹窗

nginx 防御教程之Shell脚本(二)

deny方式

零依赖|只用 Nginx|运维只需写文件

脚本

curl -sS -O https://raw.githubusercontent.com/woniu336/open_shell/main/nginx-b.sh && chmod +x nginx-b.sh && ./nginx-b.sh

然后在 Nginx 配置中引入黑名单,例如

server {
    listen 80;
    include /etc/nginx/dynamic/blacklist.conf;  # ← 关键!

    location / {
        proxy_pass http://127.0.0.1:8080;
    }
}

核心思想:

维护一个纯文本黑名单文件:/etc/nginx/blacklist.txt(每行一个 IP)

用一个 Shell 脚本自动转成 deny 配置并 重载nginx

通过 inotifywait 监听文件变化,改完即生效

配合fail2ban(cc策略)检测到403状态码,封禁,完美联动

使用方式: 运维只需编辑 /etc/nginx/blacklist.txt, 或者使用菜单2

示例内容

1.2.3.4
5.6.7.8/24

保存文件后,3 秒内自动封禁!无需任何命令!

优点: 只需一个文本文件 + 一个 Shell 脚本 完全兼容原生 Nginx

仅允许中国用户访问

脚本

curl -sS -O https://raw.githubusercontent.com/woniu336/open_shell/main/cn-nginx.sh && chmod +x cn-nginx.sh && ./cn-nginx.sh

然后在nginx站点配置

    # Include other configuration files
    include /etc/nginx/conf.d/bing-bot.conf;
    include /etc/nginx/conf.d/china-ipv4.conf;
    include /etc/nginx/conf.d/china-ipv6.conf;

    # Access control
    allow 127.0.0.1;
    allow ::1;
    deny all; 

重载生效

nginx -t
nginx -s reload

验证方法: 国内访问→ 应正常打开; 使用境外代理或VPS访问 → 应返回403 Forbidden;

CC BY-NC-SA 4.0 转载请注明
最后更新于 2025-12-20 16:22