openresty设置访问白名单
标签:openresty,nginx
alpine编译libcidr
可以使用lua-resty-iputils,但是不支持ipv6
.lua-resty-iputils的作者推荐lua-libcidr-ffi,以支持ipv6
.lua-libcidr-ffi
需要libcidr
,我使用alpine
作为基础镜像.搜了一下,貌似alpine
上没有直接可以使用的libcidr
,就自己编译个吧
...
&& curl -fSL http://www.over-yonder.net/~fullermd/projects/libcidr/libcidr-1.2.3.tar.xz -o /tmp/libcidr-1.2.3.tar.xz \
&& xz -d /tmp/libcidr-1.2.3.tar.xz && tar -xvf /tmp/libcidr-1.2.3.tar \
&& cd libcidr-1.2.3/src && make && mv libcidr.so.0 /usr/local/openresty/lualib/libcidr.so \
...
alpine
需要安装xz
,coreutils
.其中xz
用来解压,libcidr
编译的时候会用到coreutils
里面的tsort
make
后不用make DESTDIR=/your_path install
.执行make DESTDIR=/your_path install
的话会报错.其实make
执行后,就已经生成so文件了,只不过叫libcidr.so.0
.把这个文件移动到openresty
可以解析的目录就可以了
修改libcidr-ffi.lua
只是编译了libcidr
的话,运行会报无法找到模块.所以还需要修改libcidr-ffi.lua
文件,找到里面的
local cidr = ffi.load("cidr")
改为
local cidr = ffi.load("/usr/local/openresty/lualib/libcidr.so")
路径就是上面编译后移动到的路径
构建镜像的时候,记得把修改后的libcidr-ffi.lua
加到镜像里
使用lua-libcidr-ffi
whitelist_init.lua
whitelist_ips = {
"103.21.244.0/22",
}
whitelist_access.lua
local cidr = require("resty.libcidr-ffi")
local flag=false
for i, v in ipairs(whitelist_ips) do
--proxy_protocol_addr在白名单里
if cidr.contains(cidr.from_str(v), cidr.from_str(ngx.var.proxy_protocol_addr)) then
ngx.log(ngx.ERR,ngx.var.proxy_protocol_addr,' match ',v)
flag=true
break
end
end
if not flag then
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
nginx.conf
http{
init_by_lua_file whitelist_init.lua;
server{
listen 4430;
location / {
access_by_lua_file whitelist_access.lua;
}
}
}
nginx allow/deny directives
使用nginx的allow/deny指令也可以实现,不过要注意的是,allow/deny指令默认对remote_addr
过滤,如果nginx前面有反向代理,remote_addr
将会是127.0.0.1,使指令不起作用.所以需要使用ngx_http_realip_module
,修改allow/deny指令的过滤对象ngx_http_realip_module
需要编译的时候添加
--with-http_realip_module
allowed-ip.conf
allow 1.1.1.0/22;
...
nginx.conf
real_ip_header proxy_protocol;
set_real_ip_from 127.0.0.1;
include /root/allowed-ip.conf;
deny all;
- real_ip_header
Defines the request header field whose value will be used to replace the client address.
Syntax:real_ip_header field | X-Real-IP | X-Forwarded-For | proxy_protocol;
- set_real_ip_from
Defines trusted addresses that are known to send correct replacement addresses
set_real_ip_from必须要设置,否则real_ip_header不起作用
不定期更新