A Rate-Limiting HTTP Proxy(5)MVC Template/URL Rewrite/WhiteList
MVC Template
https://github.com/bungle/lua-resty-template
I copy the template related things under lualib/resty/
Adjust the nginx.conf as follow:
location / {
root lua;
default_type "text/html; charset=utf-8";
content_by_lua_file lualib/lite/mvc.lua;
}
Create HTML template file in lua/template/index.html
<html>
<head>
<meta charset="UTF-8”>
<title>{{ title }}</title>
</head>
<body>
{* content *}
</body>
</html>
{{variable}} {* string *} {% lua script %}
The controller which use the template file lua/web/index.lua
local template = require "resty.template"
local _M = {}
function _M.index()
local model = {title = "hello template", content = "<h1>content</h1>"}
template.render('template/index.html', model)
end
return _M
URL rewrite
There are 2 commands to support that. ngx.exec and ngx.redirect
function _M.exec1(uri) — NORMAL MAPPING
local rewrite_urls = {}
local queryString = ngx.var.args
if queryString == nil then queryString = "" end
rewrite_urls['/index/article'] = '/article?' .. queryString
local match_url = rewrite_urls[uri]
if match_url then
-- ngx.redirect(match_url) -- url
ngx.exec(match_url) -- url
return true
end
return false
end
WhiteList and BlackList
mvc.lua codes to support the WAF
-- waf begin
local ret, waf = pcall(require, "waf")
if ret then
local c_ret, r_ret = pcall(waf.exec)
if c_ret and r_ret then
-- c_ret success processed, r_ret redirect
return
end
end
-- waf end
The real lua/waf.lua codes
local _M = {}
function parse_ip(ip_str)
local ip_list = {}
local it, err = ngx.re.gmatch(ip_str, '([0-9]+)[.]([0-9]+)[.]([0-9]+)[.]([0-9]+)')
while true do
local m, err = it()
if err then
ngx.log(ngx.ERR, "error: ", err)
return
end
if not m then break end
ip_list[m[0]] = true
end
return ip_list
end
local white_list_str = "192.168.0.168"
local white_list = parse_ip(white_list_str)
local black_list_str = "127.0.0.1,192.168.0.168,localhost"
local black_list = parse_ip(black_list_str)
function get_client_ip()
local ip = ngx.req.get_headers()["x_forwarded_for"]
if not ip then
ip = ngx.var.remote_addr
else
ip = ngx.re.gsub(ip, ",.*", "")
end
return ip
end
function _M.exec()
local ip = get_client_ip()
ngx.log(ngx.DEBUG, 'the ip I get = ' .. ip)
-- in the white list, return directly
if white_list[ip] then
return false
end
-- black list, return 444
if black_list[ip] then
ngx.exit(444)
return true
end
end
return _M
So if I get rid of 127.0.0.1 in the whitelist, my request will be deny
http://localhost/user/index
References:
https://github.com/362228416/openresty-web-dev/tree/master/demo9
https://github.com/362228416/openresty-web-dev/tree/master/demo10
https://github.com/362228416/openresty-web-dev/tree/master/demo11
https://github.com/362228416/openresty-web-dev/tree/master/demo12