rewrite转ngx_lua的解析(openresty)

rewritengx_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的重新匹配,如果jumptrue。那么nginx将会根据修改后的uri,重新匹配新的locations,但是如果为false的话(默认为false), 就不会进行locations的重新匹配,而是修改当前请求的uri

将之对应到nginxlastbreak两种情况,jumptrue就表示rewrite使用的lastfalse则表示为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"})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容