Nginx+Lua实现动态黑名单

小编 2026-06-26 阅读:769 评论:0
介绍 通过nginx+lua+redis可以实现nginx动态从redis读取需要拒绝的ip黑名单列表,并拒绝黑名单ip的访问请求。 其中redis中的ip黑名单列表既可以人工后台手动添加,也...

介绍

通过nginx+lua+redis可以实现nginx动态从redis读取需要拒绝的ip黑名单列表,并拒绝黑名单ip的访问请求。

其中redis中的ip黑名单列表既可以人工后台手动添加,也可以用类似logstash+elasticsearch的组合,实现logstash实时读取nginx的访问日志access.log,elasticsearch储存并聚合访问日志中的访问记录,再由一个分析程序定时统计分析访问记录后判断出要加入黑名单的ip,然后将ip储存到redis中的ip黑名单列表。

nginx配置

http {
    ...
    lua_shared_dict forbidden_list 5m;
    
    location /lua {
        # lua_code_cache off;
        access_by_lua_file conf/lua/forbidden_list.lua;
        default_type \'text/html\';
        content_by_lua \'ngx.say(\"hello world\")\';
    }
}

lua配置

local redis = require(\"resty.redis\")
local ngx_log = ngx.log
local ngx_ERR = ngx.ERR
local ngx_INFO = ngx.INFO
local ngx_exit = ngx.exit
local ngx_var = ngx.var

-- 黑名单缓存60秒
local cache_idle = 60
local forbidden_list = ngx.shared.forbidden_list


local function close_redis(red)
	if not red then
		return
	end
	-- 释放连接(连接池实现)
	local pool_max_idle_time = 10000 -- 毫秒
	local pool_size = 100  -- 连接池大小
	local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
	
	if not ok then
		ngx_log(ngx_ERR, \"set redis keepalive error : \", err)
	end
end

-- 从redis获取ip黑名单列表
local function get_forbidden_list()
	local red = redis:new()
	red:set_timeout(1000)
	local ip = \"127.0.0.1\"
	local port = 6379
	local password = \"password\"
	local ok, err = red:connect(ip, port)
	if not ok then
		ngx_log(ngx_ERR, \"connect to redis error : \", err)
		close_redis(red)
		return
	end
	
	local res, err = red:auth(password)
    if not res then
        ngx_log(ngx_ERR, \"failed to authenticate: \", err)
		close_redis(red)
        return
    end
	
	local resp, err = red:smembers(\"forbidden_list\")
	if not resp then
		ngx_log(ngx_ERR, \"get redis connect error : \", err)
		close_redis(red)
		return
	end
	-- 得到的数据为空处理
	if resp == ngx.null then
		resp = nil
	end
	close_redis(red)
	
	return resp
end

-- 刷新黑名单
local function reflush_forbidden_list()
	local current_time = ngx.now()
	local last_update_time = forbidden_list:get(\"last_update_time\");
	
	if last_update_time == nil or last_update_time < (current_time - cache_idle) then
		local new_forbidden_list = get_forbidden_list();
		if not new_forbidden_list then
			return
		end
		
		forbidden_list:flush_all()
		for i, forbidden_ip in ipairs(new_forbidden_list) do
			forbidden_list:set(forbidden_ip, true);
		end
		forbidden_list:set(\"last_update_time\", current_time);
	end
end


reflush_forbidden_list()
local ip = ngx_var.remote_addr
if forbidden_list:get(ip) then
	ngx_log(ngx_INFO, \"forbidden ip refused access : \", ip)
	return ngx_exit(ngx.HTTP_FORBIDDEN)
end

redis修改黑名单

添加黑名单

SADD forbidden_list \"127.0.0.1\"

移除黑名单

SREM forbidden_list \"127.0.0.1\"

效果

[root@localhost ~]# curl http://localhost/lua
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor=\"white\">
<center><h1>403 Forbidden</h1></center>
<hr><center>openresty/1.13.6.1</center>
</body>
</html>
[root@localhost ~]# curl http://localhost/lua
hello world

日志

2018/12/23 13:10:47 [info] 4416#0: *56 [lua] forbidden_list.lua:86: forbidden ip refused access : 127.0.0.1, client: 127.0.0.1, server: localhost, request: \"GET /lua HTTP/1.1\", host: \"localhost\"
版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
标签列表