Nginx: How to set expiration for 404 responses

cachehttp-headershttp-status-code-404nginx

My nginx server acts as a proxy for another server, which sometimes returns 404s.
I want the 404 responses to be cacheable, just like 200 responses.

However, I cannot use expires, because the documentation states that:

expires works only for 200, 204, 301, 302, and 304 responses.

Note that caching of non-200 responses is perfectly possible according to the HTTP spec.

So how can I set an expiration date on 404 responses?

Best Answer

I see two options:

  1. Modify another server to provide caching headers.

  2. Use headers_more module. It allows add headers to error http responses, but you'll have to recompile nginx.

  3. Use Lua module.


Original answer

It's impossible to cache error pages on client (browser)

Probably you want to cache response from another server and it possible with proxy_cache directive. Also take a look at proxy_cache_valid directive.