作为IT工程师,我将为您提供一套完整的Nginx反向代理配置方案来防范Bot攻击。
http {
limit_req_zone $binary_remote_addr zone=botlimit:10m rate=10r/s;
server {
location / {
limit_req zone=botlimit burst=20 nodelay;
# 其他配置...
}
}
}
http {
limit_conn_zone $binary_remote_addr zone=connlimit:10m;
server {
location / {
limit_conn connlimit 10;
# 其他配置...
}
}
}
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;
}
}
location / {
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
}
location ~* (\.(svn|git|htaccess|htpasswd|env|ini|log|sh|bak|swp|sql)|~)$ {
return 403;
}
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
}
}
}
# /etc/fail2ban/filter.d/nginx-botsearch.conf
[Definition]
failregex = ^<HOST>.*"(GET|POST|HEAD).*" (404|403|400) .*$
ignoreregex =
# /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
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
server {
# 其他配置...
}
}
以上配置可根据实际业务需求进行调整,建议在测试环境验证后再应用到生产环境。