rewrite转ngx_lua的解析(openresty)

如题所述

第1个回答  2022-07-23

先看一下 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() 进行替换

其中 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)

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")

获取请求参数,之前我还以为使用 var.uri 会获取完整的 uri 包括 ? 后的参数返回字符串,后来才发现?后的都没有hhh。所以就用了这个函数。

GET www.123.com/aaa.php?a=hhh

out:

a:hhh

一般会用在判断参数的校验里面,根据不同的参数结果返回不同的页面或者改写等

与 get_uri 相反,该函数是为了设置参数

一般都会与上面的 set_uri 进行搭配使用

这个方法一帮用于在获取 http 请求中的 body 使用的,这里主要的难度是在使用方法里面。

参照: https://www.kawabangga.com/posts/3341

需要读 body 的时候是需要打开读 body 开关的,使用的方法就是先调用 ngx.req.read_body() 。

但是还会存在读不到 body 的情况就是因为请求体被存放到了零临时文件中了。这时候就是使用 ngx.req.get_body_file() 先获取到这个只读的临时文件的文件名。最后从这个文件中读出请求 body

这个方法就类似于 ngx.set_uri() 和 ngx.set_uri_args() 的部分结合版

该方法主要意思为: rewrite regrex replacement last; 内部重定向

相似回答