![是否有可能在 body_filter_by_lua_block 期间避免在 lua nginx 上进行分块传输?](https://linux22.com/image/757163/%E6%98%AF%E5%90%A6%E6%9C%89%E5%8F%AF%E8%83%BD%E5%9C%A8%20body_filter_by_lua_block%20%E6%9C%9F%E9%97%B4%E9%81%BF%E5%85%8D%E5%9C%A8%20lua%20nginx%20%E4%B8%8A%E8%BF%9B%E8%A1%8C%E5%88%86%E5%9D%97%E4%BC%A0%E8%BE%93%EF%BC%9F.png)
假设我们想要更改来自上游的响应,我们可以做的就是在该body_filter_by_lua_block
阶段使用 Lua+nginx,下面是其中的一个片段。
server {
listen 8181;
location /media {
alias /media/;
}
}
server {
listen 8080;
location /media {
proxy_pass http://localhost:8181;
# we need to keep this url since we're going to rewrite
set_by_lua_block $original_uri { return ngx.var.uri }
# when the Lua code may change the length of the response body
header_filter_by_lua_block { ngx.header.content_length = nil }
# removing (rewriting) the filters
rewrite_by_lua_block {
local uri = ngx.re.sub(ngx.var.uri, "^/media/(.*)/hls/(.*)$", "/media/hls/$2")
ngx.req.set_uri(uri)
}
# applying the bandwidth min filter
# but we can use the ngx.var.original_uri to build/select the filters
body_filter_by_lua_block {
local modified_manifest = filtering(ngx.arg[1])
ngx.arg[1] = modified_manifest
ngx.arg[2] = true
}
}
这很好用!但问题是,这样响应将使用分块传输,而有些客户端无法处理分块响应,你知道我该如何克服这个问题吗?
答案1
我通过以下方式解决了这个问题发出子请求并满足内容长度标头。
location /mmedia {
content_by_lua_block {
local uri = ngx.re.sub(ngx.var.uri, "^/mmedia/(.*)/hls/(.*)$", "/media/$1/hls/$2")
local res = ngx.location.capture(uri)
if res then
ngx.header.content_length = #res.body
ngx.print(res.body)
end
}
}