access_by_lua_block { local lim = require"resty.limit.req".new("ip_req_store", 100, 50) -- 差异化限速:VIP用户放宽限制 local rate = is_vip(ip) and200or100 lim:set_rate(rate) if lim:incoming(ip) == "rejected"then ngx.header["Retry-After"] = 5 return ngx.exit(429) end }
2. 行为分析引擎:识别恶意模式
functiondetect_abnormal(ip) local dict = ngx.shared.ip_behavior local key = ip..":pattern" -- 统计10秒内请求路径熵值 local entropy = calculate_path_entropy(ip) -- 熵值异常升高判定为扫描行为 if entropy > THRESHOLD then dict:set(key, "scanner", 600) returntrue end end
3. 分布式封禁系统(Redis版)
local redis = require"resty.redis" local red = redis:new() -- 自动拉黑高频攻击IP if req_count(ip) > 1000then red:sadd("global:blacklist", ip) red:expire(ip, 3600) end -- 全局黑名单校验 if red:sismember("global:blacklist", ip) then ngx.exit(403) end