背景
服務是采用nginx+lua實作的,在nginx的配置中存在多處(共20多處)正則判斷,期望進行優化
location ~* /test.gif {
rewrite_by_lua_file 'lua/edit.lua';
if ($query_string ~* "pd=8(&|$)") {
set $req_host inner.a.com;
proxy_pass http://127.0.0.1:8481;
}
if ($query_string ~* "pd=3(&|$)") {
set $req_host inner.b.com;
proxy_pass http://127.0.0.1:8481;
}
if ($query_string ~* "ffs=.*(\{|%7B).*(%22|\")flag(%22|\")(:|%3A)(%22|\")?1(%22|\")+.*(\}|%7D)") {
set $req_host inner.c.com;
proxy_pass http://127.0.0.1:8481;
}
}
改進方法
1、在nginx中定義pd、flag字段用來存儲pd、flag的值
set $pd 0;
set $flag 0;
2、在set_by_lua_file中使用正則進行提取pd、flag的值
set_by_lua_file:
local args = ngx.req.get_uri_args()
if args['action'] == 'test' then
ngx.var.pd = '1'
else
ngx.var.pd = '2'
end
local encodeRegex = "flow%22%3A%22([0-9]+)%22"
local normalRegex = 'flow":"([0-9]+)'
local str = 'logExtra=%7B%22st%22%3A%22other%22%2C%22rid%22%3A%22%22%2C%22pos%22%3A%220%22%2C%22flow%22%3A%2212%22%2C%22extra%22%3A%22%7B%7D%22%2C%22actionType%22%3A%22refresh_bottom%22%7D&r=l1562578644706'
local str1 = '&logExtra={"st":"other","rid":"","pos":"0","flow":"12","extra":"{}","actionType":"refresh_bottom"}&r=l1562578644706'
local normalFlow = ngx.re.match(str1, normalRegex)
local encodeFlow = ngx.re.match(str, encodeRegex)
if encodeFlow ~= nil and encodeFlow[1] ~= nil then
ngx.var.flag = encodeFlow[1]
end
if normalFlow ~= nil and normalFlow[1] ~= nil then
ngx.var.flag = normalFlow[1]
end
3、在test.gif中直接使用$pd $flag進行判斷
nginx.conf
set $flag 0;
set $pd 0;
location / {
location /tcbox {
set_by_lua_file $a '/test/set.lua';
if ($flag = 1) {
content_by_lua_file '/test/caseone.lua';
}
if ($flag = 2) {
content_by_lua_file '/test/casetwo.lua';
}
}
}