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

我想在 Lua 中修改请求头并将其重定向,我尝试了

ngx.redirect("/")

ngx.exec("/")

但我收到以下错误:

attempt to call ngx.redirect after sending out the headers

有没有一种简单的方法可以添加一个标头值并将其重定向到其他地方的 Lua? 在文档中,我没有找到任何适当的指令,还有一种方式可以在仍在使用 content_by_lua_file 的情况下完成这项工作吗?

我正在使用 openresty。

点赞
用户1058509
用户1058509

redirect method documentation 看:

请注意,调用此方法会终止当前请求的处理,并且必须在 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")
   ';
}

curl 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-30 17:36:08