tar -zxvf nginx-1.19.5.tar.gz #解压
cd nginx-1.19.5 #进入目录
./configure #配置
make #编译
make install #安装
cd /usr/local/nginx/sbin #切换到nginx命令目录
./nginx #启动nginx
# Lua
local function close_redis(redcli)
if not redcli then
return
end
--释放连接(连接池实现)
local pool_max_idle_time = 10000 --毫秒
local pool_size = 100 --连接池大小
local ok, err = redcli:set_keepalive(pool_max_idle_time, pool_size)
if not ok then
ngx_log(ngx_ERR, "set redis keepalive error : ", err)
end
end
-- 连接redis
local redis = require('resty.redis')
local redcli = redis.new()
redcli:set_timeout(1000)
local ip = "127.0.0.1" ---修改变量
local port = "6379" ---修改变量
local ok, err = redcli:connect(ip,port)
if not ok then
return close_redis(redcli)
end
local clientIP = ngx.var.remote_addr
-- increKey为请求频率,blackKey黑名单key
local incrKey = "user:"..clientIP..":request:frequency"
local blackKey = "user:"..clientIP..":black:list"
local is_black,err = redcli:get(blackKey)
if tonumber(is_black) == 1 then
ngx.exit(403)
close_redis(redcli)
end
inc = redcli:incr(incrKey)
ngx.say(inc)
if inc < 2 then
inc = redcli:expire(incrKey,1)
end
if inc > 2 then --每秒2次以上访问即视为非法,会阻止30s的访问
redcli:set(blackKey,1)
redcli:expire(blackKey,30)
end
close_redis(redcli)
启动nginx后,请求一直报错
2020/12/01 19:13:53 [error] 2101#0: *2 lua entry thread aborted: runtime error: /usr/local/openresty/nginx/lua/access_by_redis.lua:29: attempt to call field 'get_headers' (a nil value)
stack traceback:
coroutine 0:
/usr/local/openresty/nginx/lua/access_by_redis.lua: in main chunk, client: 192.168.49.1, server: localhost, request: "GET /test1 HTTP/1.1", host: "192.168.49.131"