通过openresty限制访问频率(笔记)
local resolver = require "resty.dns.resolver"local redis = require "resty.redis"
local user_agent = ngx.var.http_user_agent
local rip = ngx.var.remote_addr
local prip = resolver.arpa_str(rip)
local conn = redis:new()
conn:set_timeout(1000)
ok, err = conn:connect("10.0.10.111", 6379)
if not ok then
ngx.log(ngx.ERR, "failed to connect redis: ", err)
conn:close()
end
local r, err = resolver:new{nameservers = {"114.114.114.114", "223.5.5.5"}, retrans = 5, timeout = 2000}
if not r then
ngx.log(ngx.ERR, "failed to instantiate the resolver: ", err)
return
end
--查询user-agent是否包含指定要限制字符
if ngx.re.match(user_agent, "yyy|xxx","ijo")then
rds, err = conn:get(rip)
--查询redis里是否包含该ip,1:包含且是非法ip。0:包含且合法
if rds == "1" then
ngx.exit(502)
elseif rds == ngx.null then
--redis值为null,dns查询并记录redis
local answers, err = r:query(prip, {qtype = r.TYPE_PTR})
if not answers then
ngx.say("failed to query the DNS server: ", err)
end
if answers.errcode then
ngx.say("server returned error code: ", answers.errcode,": ", answers.errstr)
conn:set(rip,1)
end
for i, ans in ipairs(answers) do
if ngx.re.match(ans.ptrdname, "(.*)xxx.com", "ijo")then
conn:set(rip,0)
ngx.say("OK!!")
else
ngx.say("Not OK!")
conn:set(rip,1)
end
end
end
end
页:
[1]