How to display the age of an nginx cached file in headers How to display the age of an nginx cached file in headers nginx nginx

How to display the age of an nginx cached file in headers


The nginx documentation is quite exhaustive — there's no variable with the direct relative age of the cached file.

The best way would be to use the $upstream_http_ variable class to get the absolute age of the resource by picking up its Date header through $upsteam_http_date.

add_header X-Cache-Date $upstream_http_date;

For the semantic meaning of the Date header field in HTTP/1.1, refer to rfc7231#section-7.1.1.2, which describes it as the time of the HTTP response generation, so, basically, this should accomplish exactly what you want (especially if the backend runs with the same timecounter).


I spent some time attempting to solve this with the Nginx Perl module, which does not seem to have access to $upstream_http_NAME headers that would allow you to successfully calculate the current time from a timestamp header that your proxied application created during render time.

Alternatively, you could use a different caching layer architecture like Varnish Cache, which does indeed provide the Age HTTP response header:

http://book.varnish-software.com/3.0/HTTP.html#age


I made a solution that works for this, with the Lua module, in this question: Nginx: Add “Age” header, with Lua. Is this a good solution?

I'm going to post here the code, for any suggestion it would be better to discuss it in the other link, where I explain it in more detail.

map $upstream_http_Date $mapdate {    default $upstream_http_Date;     '' 'Sat, 21 Dec 2019 00:00:00 GMT';}

Inside location:

header_filter_by_lua_block {    ngx.header["Age"] = ngx.time() - ngx.parse_http_time(ngx.var.mapdate); }