在 Nginx 上使用 Lua 重定向到相同的 URL(openresty 设置)

ans*_*ulv 3 lua nginx openresty

我正在寻找修改请求标头并在 Lua 中重定向它,我已经尝试过

 ngx.redirect("/")
Run Code Online (Sandbox Code Playgroud)

 ngx.exec("/")
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

attempt to call ngx.redirect after sending out the headers
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来添加标头值并将其重定向到 Lua 中的其他位置?在文档中我没有找到任何合适的指令,有没有一种方法可以在仍然使用content_by_lua_file的同时完成类似的操作?

我正在使用 openresty。

dan*_*gpm 5

来自重定向方法文档

请注意,此方法调用会终止当前请求的处理,并且必须在 ngx.send_headers 或 ngx.print 或 ngx.say 显式响应正文输出之前调用它。

因此,请检查或使用另一个请求阶段处理程序,例如rewrite_by_lua

至于设置 header,使用ngx.header

例如:

location /testRedirect {
   content_by_lua '
     ngx.header["My-header"]= "foo"
     return ngx.redirect("http://www.google.com")
   ';
}
Run Code Online (Sandbox Code Playgroud)

卷曲http://127.0.0.1/testRedirect

输出:

location /testRedirect {
   content_by_lua '
     ngx.header["My-header"]= "foo"
     return ngx.redirect("http://www.google.com")
   ';
}
Run Code Online (Sandbox Code Playgroud)

注意:大多数网站不会接受来自重定向的自定义标头,因此在这种情况下请考虑使用 cookie。