Search code examples
nginxopenresty

How to change Content-length in body_filter_by_lua* in openresty


I am using openresty as a proxy server, which may change response from upstream. Directive header_filter_by_lua* is executed before body_filter_by_lua*. But I changed Content-length in body_filter_by_lua*, and headers has been sent at that time.

So how to set correct Content-length when response from upstream is changed in body_filter_by_lua*?

Thank you!


Solution

  • From https://github.com/openresty/lua-nginx-module#body_filter_by_lua:

    When the Lua code may change the length of the response body, then it is required to always clear out the Content-Length response header (if any) in a header filter to enforce streaming output, as in

     location /foo {
         # fastcgi_pass/proxy_pass/...
    
         header_filter_by_lua_block { ngx.header.content_length = nil }
         body_filter_by_lua 'ngx.arg[1] = string.len(ngx.arg[1]) .. "\\n"';
     }
    

    I expect that nginx would use http://greenbytes.de/tech/webdav/rfc2616.html#chunked.transfer.encoding in this case (didn't test)