Learn how Enterprise customers can configure the duration a resource is cached at Cloudflare based on the status code returned by the origin web server.
Overview
Enterprise customers can set cache TTL based on the response status from the origin web server. Cache TTL (time-to-live) refers to the duration a resource lives in the Cloudflare network before it is marked as stale or discarded from cache. Status codes are returned by a resource’s origin.
Setting cache TTL based on response status overrides the default cache behavior (standard caching) for static files and overrides cache instructions sent by the origin web server. To cache non-static assets, set a Cache Level of Cache Everything using a Page Rule. Setting no-store Cache-Control or a low TTL(max-age / s-maxage) increases requests to origin web servers and decreases performance.
Set cache TTL by response status via the Cloudflare dashboard
To set cache TTL by response status:
- Log in to your Cloudflare account.
- Select the appropriate domain.
- Click the Page Rules app.
- Click Create Page Rule.
- Enter the URL pattern to match.
- Select Cache TTL by status code.
- Enter the response code or range of response codes and select the TTL.
- (optional) Click Add a Setting to choose another response status and TTL.
- Click Save.
Use the Cloudflare API to set cache TTL by response status
curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/pagerules" \ -H "X-Auth-Email: [email protected]" \ -H "X-Auth-Key: ${CF_AUTH_KEY} \ -H "Content-Type: application/json" \ --data '{ "targets": [ { "target": "url", "constraint": { "operator": "matches", "value": "www.example.com/*" } } ], "actions": [ { "id": "cache_ttl_by_status", "value": { "200": "no-cache", "100": 5, "300-302": 20 } } ], "priority": 1, "status": "active" }'
Syntax
Provide a JSON object containing status codes and their corresponding ttls. Each key-value pair in the cache TTL by status page rule has the following syntax:
- status_code: A string such as 200, 500, etc. status_code matches the exact status code from the origin web server. Valid status codes are between 100 - 599.
- status_code_range: A "from-to" string, such as 200-299 or 400-599. Status_code_range matches any status code from the origin web server within the specified range.
- TTL: An integer that defines the duration an asset is valid in seconds or no-store or no-cache. Only positive integers including 0 are accepted.
Set cache TTL by response status via a Cloudflare Worker
The cacheTtlByStatus option is a version of the cacheTtl feature that designates a cache TTL for a request’s response status code (e.g. { "200-299": 86400, 404: 1, "500-599": 0 }).