local Redis_host = "127.0.0.1" -- Redis的IP地址 local Redis_port = "6379"
-- 连接超时时间,单位ms,不建议设置太高 local Redis_connection_timeout = 1000
local Redis_key = "ip_blacklist"
-- 缓存时间,单位 s local cache_ttl = 100
-- 以上是配置
local ip = ngx.var.remote_addr local ip_blacklist = ngx.shared.ip_blacklist local last_update_time = ip_blacklist:get("last_update_time");
-- 当缓存时间到期更新blacklist if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then
local Redis = require "resty.Redis"; local red = Redis:new();
red:set_timeout(Redis_connect_timeout);
local ok, err = red:connect(Redis_host, Redis_port);
if not ok then ngx.say("Redis connect failed: ", err) ngx.log(ngx.DEBUG, "Redis connection error while retrieving ip_blacklist: " .. err); return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) else -- local res, err = red:auth("foobared") -- 配置Redis的密码,我测试未设置密码,代码注释
--if not res then --ngx.say("Redis auth is error: ", err) --return --end red:select(0) local new_ip_blacklist, err = red:smembers(Redis_key); if err then ngx.log(ngx.DEBUG, "Redis read error while retrieving ip_blacklist: " .. err); else -- 情况本地存储 ip_blacklist:flush_all(); for index, banned_ip in ipairs(new_ip_blacklist) do ip_blacklist:set(banned_ip, true); end
-- 更新时间 ip_blacklist:set("last_update_time", ngx.now()); end end end
if ip_blacklist:get(ip) then --ngx.say(ip) ngx.log(ngx.DEBUG, "Banned IP detected and refused access: " .. ip); return ngx.exit(ngx.HTTP_FORBIDDEN); end