插件窝 干货文章 Nginx反向代理防范Bot的攻击

Nginx反向代理防范Bot的攻击

Nginx 配置 http Bot 284    来源:    2025-04-20

Nginx反向代理防范Bot攻击的配置方案

作为IT工程师,我将为您提供一套完整的Nginx反向代理配置方案来防范Bot攻击。

1. 基础防护配置

1.1 限制请求速率

http {
    limit_req_zone $binary_remote_addr zone=botlimit:10m rate=10r/s;

    server {
        location / {
            limit_req zone=botlimit burst=20 nodelay;
            # 其他配置...
        }
    }
}

1.2 限制并发连接数

http {
    limit_conn_zone $binary_remote_addr zone=connlimit:10m;

    server {
        location / {
            limit_conn connlimit 10;
            # 其他配置...
        }
    }
}

2. 高级Bot防护

2.1 User-Agent过滤

map $http_user_agent $bad_bot {
    default 0;
    ~*(googlebot|bingbot|YandexBot) 1; # 允许知名爬虫
    ~*(wget|curl|python-requests|java|nikto|scan|bot|spider|crawler) 1;
    ~*(nmap|sqlmap|metasploit|hydra) 1;
}

server {
    if ($bad_bot) {
        return 403;
    }
}

2.2 验证HTTP方法

location / {
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
}

2.3 防止扫描器探测

location ~* (\.(svn|git|htaccess|htpasswd|env|ini|log|sh|bak|swp|sql)|~)$ {
    return 403;
}

3. 使用Nginx+Lua增强防护

3.1 安装OpenResty或ngx_lua模块

http {
    lua_shared_dict bot_protection 10m;

    init_by_lua_block {
        -- 加载已知恶意IP列表
        local bad_ips = {
            "1.2.3.4",
            "5.6.7.8"
            -- 可以从外部API或文件加载
        }
        ngx.shared.bot_protection:set("bad_ips", bad_ips)
    }

    server {
        access_by_lua_block {
            local ip = ngx.var.remote_addr
            local bad_ips = ngx.shared.bot_protection:get("bad_ips")

            for _, bad_ip in ipairs(bad_ips) do
                if ip == bad_ip then
                    ngx.exit(ngx.HTTP_FORBIDDEN)
                end
            end
        }
    }
}

4. 结合Fail2Ban增强防护

  1. 安装Fail2Ban
  2. 创建Nginx日志监控规则
# /etc/fail2ban/filter.d/nginx-botsearch.conf
[Definition]
failregex = ^<HOST>.*"(GET|POST|HEAD).*" (404|403|400) .*$
ignoreregex =
  1. 配置Fail2Ban jail
# /etc/fail2ban/jail.local
[nginx-botsearch]
enabled = true
port = http,https
filter = nginx-botsearch
logpath = /var/log/nginx/access.log
maxretry = 5
findtime = 600
bantime = 86400

5. 使用ModSecurity WAF

load_module modules/ngx_http_modsecurity_module.so;

http {
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;

    server {
        # 其他配置...
    }
}

6. 推荐的综合配置方案

  1. 实施速率限制和连接限制
  2. 过滤可疑User-Agent
  3. 限制HTTP方法
  4. 阻止常见扫描路径
  5. 实施IP黑名单
  6. 结合Fail2Ban进行动态封禁
  7. 考虑使用ModSecurity或Cloudflare等专业WAF

监控与维护建议

  1. 定期检查Nginx访问日志中的异常模式
  2. 更新已知恶意IP和User-Agent列表
  3. 监控服务器性能指标,及时发现异常流量
  4. 考虑使用专业Bot管理解决方案如Cloudflare Bot Management

以上配置可根据实际业务需求进行调整,建议在测试环境验证后再应用到生产环境。