基于openresty的ip白名单控制
目的很简单,因为基于nginx的 ngx_http_access_module ip 模块有点太弱了,不灵活,可以直接使用openresty
在access_by_lua 阶段处理
预备
我们需要支持cidr格式的ip,所以需要一个灵活的ip解析处理包,
hamishforbes/lua-resty-iputils是一个不错的选择,对于openresty推荐使用opm安装
nginx 配置
- init 阶段处理数据cache
init_by_lua_file /opt/ip.lua;
ip.lua
local iputils = require("resty.iputils")
iputils.enable_lrucache()
local whitelist_ips = {
"ip",
"cidrformat"
}
whitelist = iputils.parse_cidrs(whitelist_ips)
- 请求控制
基于openresty 的 access_by_lua,可以放http, server, location, location if 这几个scope 中
access_by_lua_file /opt/acc.lua;
acc.lua
为了防止误伤,进行了实际ip的过滤处理
local headers=ngx.req.get_headers()
local iputils = require("resty.iputils")
local ip=headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr
if not iputils.ip_in_cidrs(ip, whitelist) then
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
说明
以上是一个简单的使用说明,实际中对于ip白名单,我们可以基于redis,或者类似的cache进行处理,实现动态的控制,实际上社区已经
有了类似的实现
参考资料
https://nginx.org/en/docs/http/ngx_http_access_module.html
https://github.com/hamishforbes/lua-resty-iputils
https://github.com/openresty/lua-nginx-module#access_by_lua_file
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2019-10-19 为知笔记docker 版本运行
2018-10-19 dbt 基本试用
2017-10-19 add-apt-repository 添加
2014-10-19 UNIX 时间戳 C#