rewrite轉(zhuǎn)ngx_lua的解析(openresty)
先看一下rewrite的語法規(guī)則
rewrite regrex replacement [flag] ;
就是說把url按照regex進(jìn)行正則匹配更換成replament,至于flag就是作為rewrite的方式
其中flag有4個(gè)取值:
last , break , redirect , permanent
其中
last , break 使用 ngx.req.set_uri()進(jìn)行替換
redirect , permanet 使用ngx.redirect()進(jìn)行替換
ngx.redirect(uri, status?)
其中uri就是改寫后的uri信息,status就是代表redirect或者permanent的,其中redirect代表302重定向,permanent代表301永久重定向。所以status就可以寫302(默認(rèn)值為302)或者301。
當(dāng)然status還可以寫其他的狀態(tài)碼301 302 303 307 308
舉個(gè)栗子:
rewrite ^/(.*)$ /aaa.html permanent;
=
ngx.redirect(/aaa.html , 301)
rewrite ^/(.*)$ /aaa.html redirect;
=
ngx.redirect(/aaa.html , 302) 或者 ngx.redirect(/aaa.html)
ngx.req.set_uri(uri, jump?)
uri和上面一樣代表改寫后的信息,jump參數(shù)就代表著是否進(jìn)行locations的重新匹配,如果jump為true。那么nginx將會根據(jù)修改后的uri,重新匹配新的locations,但是如果為false的話(默認(rèn)為false), 就不會進(jìn)行locations的重新匹配,而是修改當(dāng)前請求的uri
將之對應(yīng)到nginx中last和break兩種情況,jump為true就表示rewrite使用的last,false則表示為break。
舉個(gè)栗子:
rewrite ^/(.*)$ /aaa.html last;
=
ngx.req.set_uri("/aaa.html" , true)
rewrite ^/(.*)$ /aaa.html break;
=
ngx.req.set_uri("/aaa.html" , false)
=
ngx.req.set_uri("/aaa.html")
ngx.req.get_uri_args(max args)
獲取請求參數(shù),之前我還以為使用var.uri會獲取完整的uri包括?后的參數(shù)返回字符串,后來才發(fā)現(xiàn)?后的都沒有hhh。所以就用了這個(gè)函數(shù)。
舉個(gè)栗子:
GET www.123.com/aaa.php?a=hhh
local args, err = ngx.req.get_uri_args()
if err == "truncated" then
-- one can choose to ignore or reject the current request here
end
for key, val in pairs(args) do
--if type(val) == "table" then
-- ngx.say(key, ": ", table.concat(val, ", "))
--else
-- ngx.say(key, ": ", val)
--end
if key == "a" then
ngx.say(key , ":" , val)
end
end
out:
a:hhh
一般會用在判斷參數(shù)的校驗(yàn)里面,根據(jù)不同的參數(shù)結(jié)果返回不同的頁面或者改寫等
ngx.req.set_uri_args(args)
與get_uri相反,該函數(shù)是為了設(shè)置參數(shù)
ngx.req.set_uri_args("a=3&b=hello%20world")
ngx.req.set_uri("/foo", true)
一般都會與上面的set_uri進(jìn)行搭配使用
ngx.req.get_body_data()
這個(gè)方法一幫用于在獲取http請求中的body使用的,這里主要的難度是在使用方法里面。
參照:https://www.kawabangga.com/posts/3341
需要讀body的時(shí)候是需要打開讀body開關(guān)的,使用的方法就是先調(diào)用ngx.req.read_body()。
但是還會存在讀不到body的情況就是因?yàn)檎埱篌w被存放到了零臨時(shí)文件中了。這時(shí)候就是使用ngx.req.get_body_file()先獲取到這個(gè)只讀的臨時(shí)文件的文件名。最后從這個(gè)文件中讀出請求body
舉個(gè)栗子
ngx.req.read_body()
local body_str = ngx.req.get_body_data()
if nil == body_str then
local body_file = ngx.req.get_body_file()
if body_file then
body_str = read_from_file(body_file)
end
end
ngx.exec()
這個(gè)方法就類似于ngx.set_uri()和ngx.set_uri_args()的部分結(jié)合版
該方法主要意思為:rewrite regrex replacement last;內(nèi)部重定向
舉個(gè)栗子:
ngx.exec('/some-location');
ngx.exec('/some-location', 'a=3&b=5&c=6');
ngx.exec('/some-location?a=3&b=5', 'c=6');
ngx.exec("/foo",{ a = 3, b = "hello world"})