rewrite
转ngx_lua
的解析(openresty
)
先看一下rewrite
的语法规则
rewrite regrex replacement [flag] ;
就是说把url
按照regex
进行正则匹配更换成replament
,至于flag
就是作为rewrite
的方式
其中flag
有4个取值:
last , break , redirect , permanent
其中
last , break
使用 ngx.req.set_uri()
进行替换
redirect , permanet
使用ngx.redirect()
进行替换
ngx.redirect(uri, status?)
其中uri
就是改写后的uri
信息,status
就是代表redirect
或者permanent
的,其中redirect
代表302
重定向,permanent
代表301
永久重定向。所以status
就可以写302
(默认值为302)或者301
。
当然status
还可以写其他的状态码301
302
303
307
308
举个栗子:
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
参数就代表着是否进行locations
的重新匹配,如果jump
为true
。那么nginx
将会根据修改后的uri
,重新匹配新的locations
,但是如果为false
的话(默认为false
), 就不会进行locations
的重新匹配,而是修改当前请求的uri
将之对应到nginx
中last
和break
两种情况,jump
为true
就表示rewrite
使用的last
,false
则表示为break
。
举个栗子:
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)
获取请求参数,之前我还以为使用var.uri
会获取完整的uri
包括?
后的参数返回字符串,后来才发现?后的都没有hhh。所以就用了这个函数。
举个栗子:
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
一般会用在判断参数的校验里面,根据不同的参数结果返回不同的页面或者改写等
ngx.req.set_uri_args(args)
与get_uri
相反,该函数是为了设置参数
ngx.req.set_uri_args("a=3&b=hello%20world")
ngx.req.set_uri("/foo", true)
一般都会与上面的set_uri
进行搭配使用
ngx.req.get_body_data()
这个方法一帮用于在获取http
请求中的body
使用的,这里主要的难度是在使用方法里面。
参照:https://www.kawabangga.com/posts/3341
需要读body
的时候是需要打开读body
开关的,使用的方法就是先调用ngx.req.read_body()
。
但是还会存在读不到body
的情况就是因为请求体被存放到了零临时文件中了。这时候就是使用ngx.req.get_body_file()
先获取到这个只读的临时文件的文件名。最后从这个文件中读出请求body
举个栗子
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()
这个方法就类似于ngx.set_uri()
和ngx.set_uri_args()
的部分结合版
该方法主要意思为:rewrite regrex replacement last;
内部重定向
举个栗子:
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"})