Last active
February 6, 2017 09:34
-
-
Save wonderbeyond/d650c0dd9c74279c4128 to your computer and use it in GitHub Desktop.
nginx ip access limit with lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Access limitation based on predefined IP groups | |
-- TODO: 添加黑名单支持(通过 $deny_ip_groups 来指定禁止的IP分组) | |
-- | |
-- FIXME: 去掉默认允许 staff 的特性, 改为默认允许所有(allow all), 根据需要明确指定. | |
-- 这样就可以把该机制全局应用, 目前只能应用在那些能确定允许IP范围的地址(比如 /admin/). | |
-- | |
-- TODO: | |
-- 1. 扫描顺序问题? | |
-- 2. 不满足任何禁止和允许规则(如果先扫描允许规则且默认允许所有, 则没有这种情况), 如何处理? | |
-- 3. 允许和禁止的分组定义默认值如何设置? | |
local iputils = require("resty.iputils") | |
local ip_groups = require('lib.ip_groups') | |
local grps = ngx.var.allowed_ip_groups | |
if not grps or grps == '' then grps = 'staff' end | |
local x_forwarded_for = ngx.var.http_x_forwarded_for | |
if x_forwarded_for then | |
local m = ngx.re.match(x_forwarded_for, [=[[\d\.]+]=]) | |
client_ip = m and m[0] | |
else | |
client_ip = ngx.var.remote_addr | |
end | |
local white_list = ip_groups:get_parsed(grps) | |
local passed = iputils.ip_in_cidrs(client_ip, white_list) | |
if not passed then | |
ngx.log(ngx.ERR, "Denied: ", client_ip) | |
ngx.exit(ngx.HTTP_FORBIDDEN) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
location /lua { | |
set $allowed_ip_groups staff,partner; | |
access_by_lua_file /etc/nginx/lua-scripts/access_ip_limit.lua; | |
echo "Hello, Lua"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment