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

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

 ngx.redirect("/")

 ngx.exec("/")

但我收到以下错误:

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

例如:

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

curl 07002

输出:

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.

相关文章

文章浏览阅读3.7k次,点赞2次,收藏5次。Nginx学习笔记一、N...
文章浏览阅读1.7w次,点赞14次,收藏61次。我们在使用容器的...
文章浏览阅读1.4k次。当用户在访问网站的过程中遇到404错误时...
文章浏览阅读2.7k次。docker 和 docker-compose 部署 nginx+...
文章浏览阅读1.3k次。5:再次启动nginx,可以正常启动,可以...
文章浏览阅读3.1w次,点赞105次,收藏182次。高性能:Nginx ...