Nginx+Lua+Redis訪問頻率控制
阿新 • • 發佈:2019-01-28
前言:
Nginx來處理訪問控制的方法有多種,實現的效果也有多種,訪問IP段,訪問內容限制,訪問頻率限制等。
用Nginx+Lua+Redis來做訪問限制主要是考慮到高併發環境下快速訪問控制的需求。
Nginx處理請求的過程一共劃分為11個階段,分別是:
post-read、server-rewrite、find-config、rewrite、post-rewrite、 preaccess、access、post-access、try-files、content、log.
在openresty中,可以找到:
set_by_lua,access_by_lua,content_by_lua,rewrite_by_lua等方法。
那麼訪問控制應該是,access階段。
怎麼做?
1、方案
按照正常的邏輯思維,我們會想到的訪問控制方案如下:
1.檢測是否被forbidden?
=》是,forbidden是否到期:是,清除記錄,返回200,正常訪問;否,返回403;
=》否,返回200,正常訪問
2.每次訪問,訪問使用者的訪問頻率+1處理
3.檢測訪問頻率是否超過限制,超過即新增forbidden記錄,返回403
這是簡單地方案,還可以新增點枝枝葉葉,訪問禁止時間通過演算法匯入,每次凹曲線增加。
2、配置
首先為nginx新增vhost配置檔案,vhost.conf部分內容如下:
lua_package_path "/usr/local/openresty/lualib/?.lua;;" ;#告訴openresty庫地址
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
error_log /usr/local/openresty/nginx/logs/openresty.debug.log debug;
server {
listen 8080 default;
server_name localhost;
root /www/openresty;
location /login {
default_type 'text/html';
access_by_lua_file "/usr/local/openresty/nginx/lua/access_by_redis.lua" ;#通過lua來處理訪問控制
}
}
3.Access_by_redis.lua
參考了下v2ex.com的做法,redis儲存方案只做簡單地string儲存就足夠了。key分別是:
使用者登入記錄:user:127.0.0.1:time(unix時間戳)
訪問限制:block:127.0.0.1
local red = redis:new()
// 連線Redis
function M:redis()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
end
// 檢測是否forbidden,下面我們就檢測block:127.0.0.1,如果搜尋到資料,檢測時間是否過期,未過期返回403,否則直接返回200:
function M:check1()
local time=os.time() --system time
local res, err = red:get("block:"..ngx.var.remote_addr)
if not res then -- redis error
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error end
if type(res) == "string" then --if red not null then type(red)==string
if tonumber(res) >= tonumber(time) then --check if forbidden expired
ngx.exit(ngx.HTTP_FORBIDDEN)
--ngx.say("forbidden")
end
end
}
// 檢測,是否訪問頻率過高,如果過高,要拉到黑名單的,
實現的方法是,檢測user:127.0.0.1:time的值是否超標:
function M:check2()
local time=os.time() --system time
local res, err = red:get("user:"..ngx.var.remote_addr..":"..time)
if not res then -- redis error
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error
end
if type(res) == "string" then
if tonumber(res) >= 10 then -- attack, 10 times request/s
red:del("block:"..self.ip)
red:set("block:"..self.ip, tonumber(time)+5*60 ) --set block time
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
end
// 把每次訪問時間做一個自增長,user:127.0.0.1:time:
function M:add()
local time=os.time() --system time
ok, err = red:incr("user:"..ngx.var.remote_addr..":"..time)
if not ok then
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) --redis get data error
end
end
那麼,測試,強刷幾次瀏覽器,發現過一會,返回了403,ok,搞定。