总有些人喜欢来扫网站,admin/api/wp-admin/getConfig等等层出不穷。
虽然我的网站除了 typecho 基本上都是自建程序,不怕这些利用已知漏洞随机扫描的人,但是还是很烦这种,一秒钟请求几十次,然后也确实怕瞎猫碰到死耗子真给他扫出点什么东西来,所以在最近大火的国产 AI Deepseek 的帮助下搞了个 lua 脚本给 OpenResty 用。
当在一分钟内超过 20 次出现 404 或 403 错误就封禁十分钟当前 IP
在 nginx.conf 的 http 块内加入
http {
lua_shared_dict ip_errors 10m; # 存储错误计数器
lua_shared_dict ip_blacklist 10m; # 存储封禁名单
#其他原本的内容
然后在站点的 example.conf 的 server 块内加入
server {
access_by_lua_block {
local blacklist = ngx.shared.ip_blacklist
local client_ip = ngx.var.remote_addr
-- 如果使用代理,需从X-Forwarded-For获取真实IP
-- client_ip = string.match(ngx.var.http_x_forwarded_for or "", "[^,]+") or client_ip
if blacklist:get(client_ip) then
ngx.redirect("https://你的网站/ban", 302)
return
end
}
log_by_lua_block {
local status = ngx.status
if status == 403 or status == 404 then
local client_ip = ngx.var.remote_addr
-- 若使用代理,此处同样需要调整IP获取方式
local errors = ngx.shared.ip_errors
local key = "err:" .. client_ip
-- 原子递增计数器(初始值为0,过期时间60秒)
local new_count, err = errors:incr(key, 1)
if not new_count then
errors:set(key, 1, 60) -- 首次错误初始化计数器
new_count = 1
end
-- 阈值检查(20次/60秒)
if new_count >= 20 then
local blacklist = ngx.shared.ip_blacklist
-- 封禁IP 10分钟(600秒)
blacklist:set(client_ip, true, 600)
-- 清除错误计数器
errors:delete(key)
end
end
}
location /ban {
default_type text/html;
return 429 '<meta name="viewport" content="width=device-width, initial-scale=1"><center><br><br><h2>Too Many Bad Requirements.<br><br>Your IP has been temporarily blocked for 10 minutes.</h2></center>';
}
#其他原本的内容
大体上这样,已经给自己的网站用上了,测试了一下挺有效(给自己封了十分钟)
comment 评论区
star_outline 咱快来抢个沙发吧!