【问题标题】:Redirect to same URL with Lua on Nginx (openresty setup)在 Nginx 上使用 Lua 重定向到相同的 URL(openresty 设置)
【发布时间】:2015-09-17 03:24:53
【问题描述】:

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

 ngx.redirect("/")

 ngx.exec("/")

但我收到以下错误:

attempt to call ngx.redirect after sending out the headers

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

我正在使用 openresty。

【问题讨论】:

    标签: nginx lua openresty


    【解决方案1】:

    来自redirect method documentation

    请注意,此方法调用会终止当前请求的处理,并且必须在 ngx.send_headers 或 ngx.print 或 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://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。

    【讨论】:

      猜你喜欢
      • 2022-08-04
      • 2013-11-28
      • 2020-07-17
      • 2016-08-09
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      相关资源
      最近更新 更多