http {
lua_shared_dict auth_limit 10m; -- 用于存储速率限制数据的共享内存区域
server {
listen 80;
location / {
content_by_lua_block {
local function rate_limit(key, limit, period)
local auth_limit = ngx.shared.auth_limit
local count = auth_limit:get(key)
if count == nil then
auth_limit:set(key, 1, period)
elseif count + 1 > limit then
return false, "Too Many Requests"
else
auth_limit:incr(key, 1)
end
return true
end
local auth_header = ngx.var.http_authorization
if auth_header == nil then
ngx.status = ngx.HTTP_UNAUTHORIZED
ngx.say("Missing Authorization header")
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
local key = auth_header
local limit = 30 -- 每分钟限制30次请求
local period = 60 -- 速率限制的时间窗口(秒)
local ok, reason = rate_limit(key, limit, period)
if not ok then
ngx.status = ngx.HTTP_TOO_MANY_REQUESTS
ngx.say(reason)
ngx.exit(ngx.HTTP_TOO_MANY_REQUESTS)
end
-- 在这里处理请求
}
}
}
}