Skip to main content

Configuring Proxy Cache

1. Setting Up Proxy Cache Path

Directive Values Description
proxy_cache_path string Defines the cache storage path and configuration parameters

Example: Basic proxy_cache_path configuration

proxy_cache_path /var/cache/nginx/proxy_cache
    levels=1:2
    keys_zone=proxy_cache:10m
    max_size=1g
    inactive=6h
    use_temp_path=off;
Note: The keys_zone parameter is required and must be unique across the server.

Key Parameters

  • levels: Sets directory structure levels for cache files
  • keys_zone: Defines shared memory zone for cache keys
  • max_size: Maximum size of the cache storage
  • inactive: Time after which inactive cache entries are removed
  • use_temp_path: Controls whether to use temp path for cache files

2. Enabling Proxy Cache

Directive Values Description
proxy_cache_path string Defines the cache storage path and configuration parameters
proxy_cache string Specifies the cache zone to use for proxy responses
proxy_cache_valid time Sets the cache validity period for different response codes

Example: Basic Proxy Cache Configuration

proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
    listen 80;
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 301 302 10m;
        proxy_cache_valid 404 1m;
        proxy_pass http://backend;
    }
}
Note: The proxy_cache_path directive must be defined in the http context, while proxy_cache is used in the location context.
Warning: Ensure sufficient disk space is allocated for the cache directory to prevent performance degradation.

3. Setting Cache Validity

Directive Values Description
proxy_cache_valid 1h, 30m, 1d Sets cache validity for different response codes
proxy_cache_valid 200 1h, 404 1m Cache specific response codes for specified time

Example: Setting cache validity for different response codes

proxy_cache_valid 200 1h;
proxy_cache_valid 404 1m;
proxy_cache_valid 500 30s;
Note: The proxy_cache_valid directive allows fine-grained control over how long different types of responses are cached.

4. Configuring Cache Key

Directive Values Description
proxy_cache_key $scheme$proxy_host$uri?$query_string Defines the cache key for proxy responses. Default value includes scheme, host, URI, and query string.

Example: Custom Cache Key

proxy_cache_key "$scheme$proxy_host$uri?$query_string";
Note: The default cache key includes the scheme, host, URI, and query string. You can customize it to include additional variables like cookies or headers.

5. Bypassing Cache

Directive Description Values Notes
proxy_cache_bypass Controls when to bypass the cache $http_if_modified_since, $http_user_agent, etc. Can use variables to conditionally skip cache
proxy_no_cache Controls when to not cache response $http_if_modified_since, $http_user_agent, etc. Used to prevent caching under certain conditions

Example: Bypass cache based on user agent

location / {
    proxy_pass http://backend;
    proxy_cache my_cache;
    proxy_cache_bypass $http_user_agent;
    proxy_no_cache $http_user_agent;
}
Note: The proxy_cache_bypass directive allows bypassing the cache based on a condition, while proxy_no_cache prevents caching entirely under specific conditions.

6. Setting No Cache Conditions

Directive Values Description
proxy_no_cache string Defines conditions under which the response will not be cached.

Example: proxy_no_cache with multiple conditions

location /api/ {
    proxy_pass http://backend;
    proxy_no_cache $http_authorization $http_cookie;
}
Note: The proxy_no_cache directive allows you to define conditions under which a response should not be cached, even if it would otherwise qualify for caching. This is useful for ensuring that sensitive or dynamic content isn't cached.

7. Using Cache Lock

Cache locking prevents multiple requests for the same resource from simultaneously fetching and caching the content, reducing server load and ensuring consistency.

Directive Values Description
proxy_cache_lock on | off Enables or disables cache locking. Default is off.
proxy_cache_lock_timeout time Timeout for cache lock. Default is 5s.
proxy_cache_lock_age time Maximum age of a cached entry while holding the lock. Default is 5s.

Example: Enabling Cache Lock

location / {
    proxy_cache my_cache;
    proxy_cache_lock on;
    proxy_cache_lock_timeout 10s;
    proxy_cache_lock_age 5s;
}
Note: Cache locking is particularly useful in high-concurrency environments where many clients may request the same content simultaneously.

8. Setting Cache Methods

Method Description Notes
proxy_cache_method Specifies the HTTP methods that can be cached. By default, only GET and HEAD requests are cached. Other methods like POST, PUT, DELETE are not cached unless explicitly allowed.
proxy_cache_method POST Allows caching of POST requests. Use with caution as it may lead to inconsistent cache states if the request body changes.
proxy_cache_method PUT Allows caching of PUT requests. Similar to POST, can cause cache inconsistency if used with mutable content.
proxy_cache_method DELETE Allows caching of DELETE requests. Not commonly used; typically not recommended for caching.

Example: Enabling Cache for POST Requests

location /api/ {
    proxy_cache my_cache;
    proxy_cache_method POST;
    proxy_pass http://backend;
}
Note: When enabling caching for non-GET/HEAD methods, ensure that the backend service handles such requests consistently to avoid stale or incorrect cached content.

9. Adding Cache Status Header

Directive Values Description
proxy_cache_use_stale error, timeout, invalid_header, updating, http_500, http_502, http_503, http_504 Controls when a stale cached response can be used
proxy_cache_valid 200 1h, 404 1m, any 5m Defines how long to cache responses based on status code
proxy_cache_status MISS, HIT, EXPIRED, BYPASS, STALE, UPDATING, REVALIDATED Response header indicating cache status of the request

Example: Adding Cache Status Header

location / {
    proxy_cache my_cache;
    proxy_cache_valid 200 1h;
    proxy_cache_valid 404 1m;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    add_header X-Cache-Status $upstream_cache_status;
}

10. Purging Cache

Directive Description Usage
proxy_cache_purge Defines the conditions under which a cached response can be purged. proxy_cache_purge cache_name "http://example.com/path";

Example: Purging Cache by URL

location / {
    proxy_cache my_cache;
    proxy_cache_purge "http://$host$request_uri";
}

Example: Purging Cache with Specific Key

location / {
    proxy_cache my_cache;
    proxy_cache_key "$scheme$proxy_host$request_uri";
    proxy_cache_purge my_cache "http://example.com/path";
}
Note: The proxy_cache_purge directive requires the ngx_cache_purge module to be installed.
Warning: Ensure that the purge URL is protected to prevent unauthorized cache purging.

Key Points

  • proxy_cache_purge allows selective cache removal based on URL or key.
  • It is essential to secure the purge endpoint to avoid abuse.
  • The ngx_cache_purge module must be installed to use this feature.

11. Configuring Cache Revalidation

Directive Description Values Notes
proxy_cache_valid Sets cache validity for different response codes 200 1h, 404 1m Can be used with proxy_cache_valid to set different cache times for different status codes
proxy_cache_revalidate Enables revalidation of cached responses on, off When enabled, Nginx checks if the cached response is still valid before serving it
proxy_cache_use_stale Allows using stale cached content when the origin server is unavailable error, timeout, invalid_header, updating, http_500, http_502, http_503, http_504 Can be used in combination with proxy_cache_revalidate to provide fallback behavior

Example: Configuring Cache Revalidation

location / {
    proxy_cache my_cache;
    proxy_cache_revalidate on;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    proxy_cache_valid 200 1h;
    proxy_cache_valid 404 1m;
}

12. Setting Cache Background Update

Directive Values Description
proxy_cache_background_update on | off Enables or disables background updates of stale cache entries.

Example: Enabling Background Update

location / {
    proxy_cache my_cache;
    proxy_cache_background_update on;
    proxy_cache_valid 200 1h;
    proxy_pass http://backend;
}
Note: When proxy_cache_background_update is enabled, Nginx will serve stale content while updating the cache in the background.

Was this article helpful?