基于openresty的ip白名单控制

您所在的位置:网站首页 openresty配置ip地址转发 基于openresty的ip白名单控制

基于openresty的ip白名单控制

2023-09-26 10:30| 来源: 网络整理| 查看: 265

目的很简单,因为基于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



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3