proxy_cache_valid

The `proxy_cache_valid` directive defines the duration for which a cached response is considered valid based on the response status code. — NGINX HTTP Core

proxy_cache_valid
httpserverlocation
Синтаксисproxy_cache_valid status code time period;
По умолчаниюnone
Контекстhttp, server, location
МодульNGINX HTTP Core
Аргументы1+

Описание

The `proxy_cache_valid` directive configures the caching mechanism in NGINX by specifying how long a cached response should be retained for certain HTTP status codes. This directive is particularly beneficial when you want to control the cache duration based on different types of responses returned by a proxied server. For example, you might want to cache successful responses (HTTP 200) for a longer period compared to error responses (like HTTP 500). By default, cached responses are based on the `proxy_cache_use_stale` and `proxy_cache_revalidate` settings unless a specific time-to-live (TTL) is provided with this directive. The directive accepts one or more pairs of arguments: the HTTP status code(s) and the time period (which can be specified in seconds, minutes, hours, or days). For instance, you could write `proxy_cache_valid 200 1h;` to cache HTTP 200 responses for one hour. By using multiple lines, you can specify different time periods for various status codes, allowing for fine-tuned caching behavior appropriate to your application's needs. It is important to note that the caching behavior can also be influenced by additional directives like `proxy_cache`, which must be enabled for `proxy_cache_valid` to take effect.

Пример конфига

location /api {
    proxy_pass http://backend;
    proxy_cache my_cache;
    proxy_cache_valid 200 1h;
    proxy_cache_valid 404 10m;
}

Not having `proxy_cache` enabled will cause this directive to have no effect.

If no cache is being served when a response is requested, the response will not be cached even if this directive is defined.

Be careful with status codes; incorrectly specified codes may lead to unintended caching behavior.