基于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

posted on   荣锋亮  阅读(2083)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.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#

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示