Learn how the Cache Key Template lets customers control how Cloudflare creates Cache Keys for domains on Enterprise plans.
Overview
A Cache Key is an identifier that Cloudflare uses for a file in our cache. The Cache Key Template defines this identifier for a given HTTP request. For example, consider the following HTTP request on a TLS connection:
GET /logo.jpg HTTP/1.1 Host: www.cloudflare.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36 Accept: image/jpg
The default Cache Key constructed from this request combines aspects such as Cloudflare Zone ID, scheme, hostname, and path into a Cache Key similar to 1234:https://www.example.com/foo.jpg
There are a couple of common reasons to change the Cache Key Template:
- Fragment the cache so one URL is stored in multiple files. For example, to store different files based on a specific query string in the URL.
- Consolidate the cache so different HTTP requests are stored in the same file. For example, to remove the Origin header added to Cloudflare Cache Keys by default.
For cross-origin requests, such as one from anotherdomain.com to example.com, the Origin HTTP request header results in a Cache Key with the ${header:origin} token populated:
anotherdomain.com::https://www.example.com/something
A Cache Level of Ignore Query String creates the following Cache Key:
${header:origin}::${scheme}://${host_header}${uri_iqs}
${uri_iqs} is replaced with the request path excluding the query string, so a request for http://example.com/file.jpg?something=123 creates the following Cache Key:
::http://example.com/file.jpg
Understand the Cache Key settings
The following fields control the Cache Key Template:
Query String
Controls which URL query string parameters go into the Cache Key.
You can include specific query string parameters or exclude them using the respective fields. When you include a query string parameter, the value of the query string parameter is used in the Cache Key.
Example: For a url like https://www.example.com/?foo=bar, if you include the query string foo, then bar appears in the Cache Key.
Exactly one of include or exclude is expected.
Usage notes:
- To include all query string parameters (the default behavior), use include: "*"
- To ignore query strings, use exclude: "*"
- To include most query string parameters but exclude a few, use the “exclude” field and it’s assumed the other query string parameters are included.
Headers
Controls what headers go into the Cache Key. Similar to Query String, you can include specific headers, or exclude default headers.
Including a header results in that header value being included in the Cache Key. For example, if an HTTP request contains an HTTP header like “X-Auth-API-key: 12345”, and you include the X-Auth-API-Key header in your Cache Key Template, then 12345 appears in the Cache Key.
To check for the presence of a header without including its actual value, use the check_presence option.
Currently, only the Origin header can be excluded. The Origin header is always included unless explicitly excluded. Including the Origin header in the Cache Key is important to enforce CORS. Additionally, you cannot include the following headers:
- Headers that have high cardinality and risk sharding the cache
- accept
- accept-charset
- accept-encoding
- accept-datetime
- accept-language
- referer
- user-agent
- Headers that re-implement cache or proxy features
- connection
- content-length
- cache-control
- if-match
- if-modified-since
- if-none-match
- if-unmodified-since
- range
- upgrade
- Headers that are covered by other Cache Key features
- cookie
- host
- Headers that are specific to Cloudflare that are prefixed with cf-, e.g. cf-ray
- Headers that are already included in the custom Cache Key template
- origin
Host
Which host header you want to include in the Cache Key.
- If resolved: false, then Cloudflare includes the Host header in the HTTP request sent to the origin
- If resolved: true, then Cloudflare includes the Host header that was resolved to get the origin IP for the request. This may be different from the Host header actually sent if the Cloudflare Resolve Override feature is used.
Cookie
Like query_string or header, this controls what cookies appear in the Cache Key. You can either include the cookie value, or just check for the presence of a particular cookie.
Usage notes:
- You cannot include cookies that are specific to Cloudflare. Cloudflare cookies are prefixed with __cf, e.g. __cfuid
User features
These fields add features about the end-user (client) into the Cache Key.
- device_type classifies a request as “mobile”, “desktop”, or “tablet” based on the User Agent
- geo includes the client’s country, derived from the IP address
lang includes the first language code contained in the Accept-Language header sent by the client
Create a Custom Cache Key
There are two ways to change a Cache Key Template, through a Page Rule or through the Cloudflare API. Before making changes, refer to the Understand the Cache Key settings section above to learn about the available settings.
Update Cache Key Template via Cloudflare UI
- Log in to your Cloudflare account.
- Select the domain that requires changes to the Cache Key Template.
- Click the Rules app.
- Click the Page Rules tab.
- Enter the URL to match.
- Select Custom Cache Key from the settings dropdown.
- Select the appropriate Query String setting.
- (Optional) Click Advanced and enter appropriate settings for:
- Headers
- Cookie
- Host
- User Features
Refer to Understand the Cache Key settings section above for details on the settings available under the Advanced dropdown.
Update Cache Key Template via Cloudflare API
Cache Key Template is a page rule. You can add, view, edit, or delete the Cache Key Template just like any other page rule. See an overview of page rules here: https://api.cloudflare.com/#page-rules-for-a-zone-properties
The Cache Key Template has a page rule ID of cache_key_fields. The value accepts a JSON blob. This documentation focuses on how to set the value of this ID.
Create a new Cache Key Template
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_key_fields", "value": { "header": { "include": ["h1", "h2"], }, "query_string": { "include": ["foo", "bar"] } } } ], "priority": 1, "status": "active" }'
Example
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/pagerules" \ -H "X-Auth-Email: $CF_EMAIL" \ -H "X-Auth-Key: $CF_TOKEN" \ -H "Content-Type: application/json" \ --data '{"targets":[{"target":"url","constraint":{"operator":"matches","value":"example.com/"}}],"actions":[{"id":"cache_key_fields","value":{"query_string":{"include":"*"},"host":{"resolved":false},"user":{"lang":false,"geo":false,"device_type":true}}}],"priority":1,"status":"active"}'
Values for Cache Key Template
The value field accepts a JSON object. The object has the following definition:
{ "query_string": { "include": String array || "*", "exclude": String array || "*" }, "header": { "include": String array, "exclude": String array, "check_presence": String array }, "host": { "resolved": boolean }, "cookie": { "include": String array, "check_presence": String array }, "user": { "device_type": boolean, "geo": boolean, "lang": boolean } }
Default values
{ "query_string": { "include": "*", "exclude": [] }, "header": { "include": ["origin"], "exclude": [], "check_presence": [] }, "host": { "resolved": false }, "cookie": { "include": [], "check_presence": [] }, "user": { "device_type": false, "geo": false, "lang": false } }
Purge a Cache Key resource
Purge resources that use Cache Keys via the Cloudflare API.
If you use Cloudflare Purge by URL, include the headers and query strings that are in your custom Cache Key. To purge device_type or geo, use include CF-Device-Type or CF-IPCountry. lang cannot currently be purged. Purge by Tag / Host & Purge Everything are not impacted by the use of custom Cache Keys.
Purge by device type
For a Cache Key based on device type, purge the asset by passing the CF-Device-Type header with the API purge request (valid headers include mobile, desktop, and tablet):
Here is an example API request to purge all mobile assets on the root web page:
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_tag}/purge_cache" -H "X-Auth-Email: [email protected]" -H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" -H "Content-Type: application/json" --data '{"files":[{"url":"http://my.website.com/","headers":{"CF-Device-Type":"mobile"}}]}'
Purge by geo
Purge resources for a location-based Cache Key by specifying the two-letter country code (Spain is used in the example below):
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_tag}/purge_cache" -H "X-Auth-Email: [email protected]" -H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" -H "Content-Type: application/json" --data '{"files":[{"url":"http://my.website.com/", "headers":{"Cf-Ipcountry":"ES"}}]}'