1

I am doing simple caching with nginx. It works fine for 200 responses, but 404 responses do not "hit" the cache logic for some reason, and I do not understand why.

What I mean by "doesn't hit the cache logic", is based on my add_header X-Cached. This header doesn't appear at all if it's a 404 response.

404 response:

< HTTP/1.1 404 Not Found
< Server: nginx
< Date: Mon, 05 Dec 2016 09:54:34 GMT
< Content-Type: application/json
< Content-Length: 55
< Connection: keep-alive
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate
< Pragma: no-cache

200 response:

< HTTP/1.1 200 OK
< Server: nginx
< Date: Mon, 05 Dec 2016 09:54:56 GMT
< Content-Type: application/json
< Content-Length: 1186
< Connection: keep-alive
< Set-Cookie: PHPSESSID=5hq364dphuo8ka26sbcadiak74; path=/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate
< Pragma: no-cache
< X-Cached: MISS

Relevant nginx config:

location / {
    try_files $uri /index.php$is_args$args;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;

    fastcgi_cache_key $request_uri?$is_args$args;
    fastcgi_cache CACHENAME;
    fastcgi_cache_valid 200 90d;
    fastcgi_cache_valid 404 365d;
    fastcgi_cache_use_stale updating error timeout invalid_header http_404 http_500;

    fastcgi_cache_methods GET HEAD;
    fastcgi_ignore_headers Cache-Control Set-Cookie Expires X-Accel-Expires Vary;

    add_header X-Cached $upstream_cache_status;
}

My application is a REST API, so the response of 404 is just saying that the route returned false response. I want this response cached.

What am I doing wrong? Thanks for any ideas!

Iskar
  • 241
  • 1
  • 8
  • 1
    [`add_hader`](http://nginx.org/r/add_header). You should use `always` flag – Alexey Ten Dec 05 '16 at 11:48
  • @AlexeyTen aha, great, so it actually *has* been hitting cache properly, it just didn't say. Not sure how I missed that, so thanks much! Please comment it as the answer. – Iskar Dec 05 '16 at 13:11

1 Answers1

1

Alexey mentioned that I was missing the always flag for my add_header directive.

add_header adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307.

As my application responded 404, it was still hitting nginx's cache properly, but add_header was never sent as a result.

Iskar
  • 241
  • 1
  • 8