How do I cache content in CloudFront based on HTTP headers?
Last updated: 2022-04-14
I want to cache content in Amazon CloudFront based on HTTP headers. How can I do this?
To configure your distribution to cache content based on HTTP headers, do one of the following:
- Create a cache policy and attach it to a behavior in the distribution
- Edit the settings of an existing legacy cache behavior in the distribution
It's a best practice to create a new cache policy to cache content. You can customize your configuration more with a new cache policy instead of editing a legacy distribution.
Important: You can’t configure CloudFront to cache based on request header value for header types Connection, Host (for Amazon S3 origins), Proxy-Authorization, TE, or Upgrade. For more information, see Selecting the headers to base caching on.
Create a cache policy
- Create a cache policy using the CloudFront console.
- Under TTL settings, enter the values for Minimum TTL, Maximum TTL, and Default TTL to manage the amount of time that CloudFront caches objects. By default, the cached files will automatically expire after 24 hours.
- Under Cache key settings, for Headers, choose Include the following headers.
- From the Add header dropdown list, select your headers, or select Add custom to add a custom header.
- Complete all other settings of the cache policy based on the requirements of the behavior that you're attaching the policy to. Then, choose Create.
- After you create the cache policy, follow the steps to attach the policies to the relevant behavior of your CloudFront distribution.
Editing the settings of an existing behavior
- Open CloudFront console, and then choose your distribution.
- Choose the Behaviors tab. Then, choose the path that you want to cache the content based on selected HTTP headers.
- Choose Edit.
- Under Cache key and origin requests, confirm that Legacy cache settings is selected.
If Legacy cache settings isn't selected, follow the steps in the previous section to create a cache policy.
If Legacy cache settings is selected, do the following:
For Headers, select Include the following headers.
From the Add header dropdown list, select the headers that you want to cache.
- To manage the cache duration for the CloudFront cache, under Object Caching, choose Customize. Then specify values in the Minimum TTL, Default TTL, and Maximum TTL fields. For more information, see Object caching.
- Choose Save Changes.
Note: To change the cache duration for an individual file, configure your origin to add a Cache-Control max-age directive, Cache-Control s-maxage directive, or Expires header. For more information, see Using headers to control cache duration for individual objects.
For Amazon Simple Storage Service (Amazon S3) origins, add metadata for header values to manage the cache expiration of individual objects. For more information, see Adding headers to your objects using the Amazon S3 console.