目的很簡單,因為基於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