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

前端之家收集整理的这篇文章主要介绍了在Nginx上使用Lua重定向到相同的URL(openresty设置) 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

  1. ngx.redirect("/")

  1. ngx.exec("/")

但我收到以下错误

  1. attempt to call ngx.redirect after sending out the headers

有没有一种简单的方法添加标头值并将其重定向到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.

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

例如:

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

curl 07002

输出

  1. HTTP/1.1 302 Moved Temporarily
  2. Server: openresty
  3. Date: Tue,30 Jun 2015 17:34:38 GMT
  4. Content-Type: text/html
  5. Content-Length: 154
  6. Connection: keep-alive
  7. My-header: foo
  8. Location: http://www.google.com
  9. <html>
  10. <head><title>302 Found</title></head>
  11. <body bgcolor="white">
  12. <center><h1>302 Found</h1></center>
  13. <hr><center>Nginx</center>
  14. </body>
  15. </html>

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

猜你在找的Nginx相关文章