【问题标题】:Nginx access_by_lua_block not executed in case of 3XX redirects在 3XX 重定向的情况下不执行 Nginx access_by_lua_block
【发布时间】:2020-09-30 04:47:21
【问题描述】:

我在我的 nginx 配置中使用access_by_lua_block 来添加/修改自定义请求标头(比如说ngx.req.set_header("foo", "bar"))。在向客户端返回任何响应之前,我正在以ngx.var["http_foo"] 的形式访问header_filter_by_lua_block 中的这些标头。 如果将请求传递到上游,这可以正常工作,但是在重定向的情况下它不起作用。 所以基本上,

这有效(无重定向)。

location /abc {
   proxy_pass some_upstream;

   access_by_lua_block {
      ngx.req.set_header("foo", "bar")
   }

   header_filter_by_lua_block {
     ngx.header["foo2"] = ngx.var["http_foo"] # this is correctly getting the value of "foo" header set above
   }
}

这不起作用(使用重定向)

location /abc {
   access_by_lua_block {
      ngx.req.set_header("foo", "bar")
   }

   header_filter_by_lua_block {
     ngx.header["foo2"] = ngx.var["http_foo"] # this is not getting the value of "foo" header set above
   }

   return 301 xyz.com;
}

仅在重定向的情况下不会执行 access_by_lua_block(返回 301 语句)。我不明白为什么会这样?因为access_by_lua_block在内容阶段之前有一个执行优先级(link

【问题讨论】:

    标签: nginx lua nginx-reverse-proxy nginx-location openresty


    【解决方案1】:

    据我了解,return 指令的执行发生在重写阶段,而在这种情况下,访问阶段根本不会执行。您可以尝试将access_by_lua_block 更改为rewrite_by_lua_block 看看会发生什么。

    更新

    第一次尝试解决这个问题没有任何结果。事实上,作为rewrite_by_lua states 的 lua-ngx-module 文档:

    请注意,此处理程序总是在标准 ngx_http_rewrite_module 之后运行

    您还可以尝试在rewrite_by_lua_block 内进行重定向:

    location /abc {
       rewrite_by_lua_block {
          ngx.req.set_header("foo", "bar")
          ngx.redirect("xyz.com", 301)
       }
    
       header_filter_by_lua_block {
         ngx.header["foo2"] = ngx.var["http_foo"] # this is not getting the value of "foo" header set above
       }
    }
    

    【讨论】:

    • 您好,感谢您的回复。我也试过 rewrite_by_lua_block ,仍然无法访问请求头。
    • @VinayMundada 再试一次,请检查更新的答案。同样,这只是一个猜测。
    猜你喜欢
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2015-12-10
    • 2012-05-22
    相关资源
    最近更新 更多