在 Nginx 上重定向到与 Lua 相同的 URL(openresty 设置)
Redirect to same URL with Lua on Nginx (openresty setup)
我想修改一个请求 header 并在 Lua 中重定向它,我试过了
ngx.redirect("/")
和
ngx.exec("/")
但我收到以下错误:
attempt to call ngx.redirect after sending out the headers
是否有直接的方法来添加 header 值并将其重定向到 Lua 中的其他位置?在文档中我没有找到任何合适的指令,有没有办法在仍然使用 content_by_lua_file 的同时完成这样的事情?
我正在使用 openresty。
来自redirect method documentation:
Note that this method call terminates the processing of the current request and that it must be called before ngx.send_headers or explicit response body outputs by either ngx.print or 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")
';
}
输出:
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>
注意:大多数网站不接受来自重定向的自定义 header,因此请考虑在这种情况下使用 cookie。
我想修改一个请求 header 并在 Lua 中重定向它,我试过了
ngx.redirect("/")
和
ngx.exec("/")
但我收到以下错误:
attempt to call ngx.redirect after sending out the headers
是否有直接的方法来添加 header 值并将其重定向到 Lua 中的其他位置?在文档中我没有找到任何合适的指令,有没有办法在仍然使用 content_by_lua_file 的同时完成这样的事情?
我正在使用 openresty。
来自redirect method documentation:
Note that this method call terminates the processing of the current request and that it must be called before ngx.send_headers or explicit response body outputs by either ngx.print or 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")
';
}
输出:
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>
注意:大多数网站不接受来自重定向的自定义 header,因此请考虑在这种情况下使用 cookie。