1

I'm using using Nginx as Reverse Proxy and Caching the proxied response from my upstream server.

So, I need to add a Content-Length header to this cached files before sending to my client.

I've tried adding the $upstream_response_length variable to location directive, but it doesn't work.

location /files/ {

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_buffering on;
    chunked_transfer_encoding off;

    ##PROXY CACHE CONFIG

    proxy_cache my_cache;
    add_header X-Proxy-Cache $upstream_cache_status;
    proxy_ignore_headers Cache-Control;
    proxy_cache_valid any 30m;
    add_header Content-Length $upstream_response_length;

    proxy_pass http://upstream_server;

}

How can I do this?

Jesse Nickles
  • 1,435
  • 1
  • 17
  • 25
Miguel Torre
  • 11
  • 1
  • 2

1 Answers1

1

As noted here:

nginx removes Content-Length header (and uses chunked if possible) if resulting length after processing isn't known. This happens e.g. if you use gzip, ssi, sub or addition modules.

So it's likely you're using one of those.

I believe that NGINX "knows" content length of cached pages, so it should send Content-Length for them by default, unless you use those modules.

Danila Vershinin
  • 8,725
  • 2
  • 29
  • 35
  • This is accurate, and keep in mind gzip affects primarily `text/html` content so if you want to have `Content-Length` for e.g. ETags or whatever to work properly on HTML files, then you have to disable gzip on your Nginx server and/or CDN. – Jesse Nickles Sep 07 '22 at 07:36