0
0
NginxHow-ToBeginner · 3 min read

How to Use proxy_cache_valid in Nginx for Cache Control

Use proxy_cache_valid in Nginx to set how long cached responses stay valid based on their HTTP status codes. It defines cache duration like proxy_cache_valid 200 10m; to cache 200 OK responses for 10 minutes.
📐

Syntax

The proxy_cache_valid directive sets the cache duration for responses based on their HTTP status codes.

Its basic form is:

  • proxy_cache_valid — Cache responses with the given status for the specified time.
  • You can specify multiple status codes separated by spaces.
  • time can be in seconds (s), minutes (m), hours (h), or days (d).
nginx
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid any 5m;
💻

Example

This example shows how to cache successful responses (200 and 302) for 10 minutes, 404 errors for 1 minute, and all other responses for 5 minutes.

nginx
http {
    proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m max_size=100m inactive=60m use_temp_path=off;

    server {
        listen 80;

        location / {
            proxy_pass http://backend_server;
            proxy_cache my_cache;
            proxy_cache_valid 200 302 10m;
            proxy_cache_valid 404 1m;
            proxy_cache_valid any 5m;
        }
    }
}
⚠️

Common Pitfalls

  • Not specifying status codes: If you omit proxy_cache_valid, Nginx may not cache responses as expected.
  • Using any incorrectly: any applies to all status codes not explicitly listed, so order and specificity matter.
  • Setting too long cache times for error codes: Caching errors like 500 for long can serve stale error pages.
  • Forgetting to enable proxy_cache: Without enabling proxy_cache, proxy_cache_valid has no effect.
nginx
Wrong:
proxy_cache_valid 10m;

Right:
proxy_cache_valid 200 10m;
📊

Quick Reference

DirectiveDescriptionExample
proxy_cache_valid Sets cache time for specified HTTP status codesproxy_cache_valid 200 5m;
proxy_cache_valid any Sets cache time for all other status codesproxy_cache_valid any 1m;
Multiple statusesCache multiple statuses with one directiveproxy_cache_valid 200 302 10m;
Time unitsSupports s, m, h, d for seconds, minutes, hours, daysproxy_cache_valid 404 30s;

Key Takeaways

Use proxy_cache_valid to control how long Nginx caches responses by HTTP status code.
Specify exact status codes or use 'any' for all others to set cache durations.
Always enable proxy_cache for proxy_cache_valid to work.
Avoid caching error responses for too long to prevent serving stale errors.
Use time units like s, m, h, d to define cache duration clearly.