3

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

 ngx.redirect("/")

 ngx.exec("/")

但我收到以下错误:

attempt to call ngx.redirect after sending out the headers

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

我正在使用openresty。

4

1 回答 1

3

重定向方法文档

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

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

至于设置标题,请使用ngx.header

例如:

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

卷曲http://127.0.0.1/testRedirect

输出:

HTTP/1.1 302 Moved Temporarily
Server: openresty
Date: Tue, 30 Jun 2015 17:34:38 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
My-header: foo
Location: http://www.google.com

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

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

于 2015-06-30T17:36:08.227 回答