I an proxying to an external JSON api and am trying to cache the proxy responses. To determine if the proxy cache is working I have added

add_header X-Cached $upstream_cache_status;

and always see a MISS value.

My nginx config location:

location /api/tides {
  proxy_hide_header Cache-Control;
  proxy_ignore_headers Cache-Control;
  proxy_cache worldtidecache;
  proxy_set_header Host www.worldtides.info;
  proxy_pass https://example.com/api/$query_string;
  add_header X-Cached $upstream_cache_status;

Prior to that I have proxy_cache_path set

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=worldtidecache:100m max_size=1g inactive=48h use_temp_path=off;

www-data has read/write access to /var/cache/nginx

I am assuming that proxy_buffering is set to on as I don't have any explicit setting for this.

The nginx config is valid. I have tested it with nginx -c nginx.conf -t:

╰─sudo nginx -c nginx.conf -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

I've tailed both the error.log and access.log and I don't see anything that would indicate why the caching wouldn't be working.

The headers I get from the proxy response:

Server: nginx/1.11.13
Date: Sun, 20 Aug 2017 14:01:59 GMT
Content-Type: text/json; charset=utf-8
Content-Length: 2976
Connection: keep-alive
Content-Encoding: gzip
X-Cloud-Trace-Context: 38faabaa5ada170536632bb55a0ddf00;o=1
Vary: Accept-Encoding
X-Cached: MISS

I'm stuck at this point. I don't know what else would be causing nginx to not cache. There isn't any cache busting happening on the requests like a unique query param, the url is consistent on each request. Outside of setting the header to the cache attempt result I don't know of any other way to log what the proxy caching is doing.

  • How do the does the response headers look for https://www.example.com/api/$query_string? Does $query_string possibly include a cache killer? – Tero Kilkanen Aug 20 '17 at 15:21

Twitter to the rescue: https://twitter.com/btucker/status/899309118137057286

proxy_cache_valid any 48h;
  • I don't know why cache works on other nginx, but in my last project I had to add this proxy_cache_valid and started to cache. Strange. – jotacor Dec 6 '17 at 14:14

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.