Sub topic 7
Cache behaviors and path patterns
This chapter shows how one CloudFront distribution applies different rules to different URL paths. It assumes you have read the earlier chapters on distributions, Origin Access Control, and the bucket policy. It also assumes you can read a CloudFormation YAML excerpt and use curl to inspect response headers.
What a cache behavior is
A cache behavior is a bundle of settings tied to a path pattern. When a viewer request arrives, CloudFront compares the request path with the patterns in your distribution. The first matching pattern decides how the request is handled.
Each behavior sets:
- The origin to fetch from on a cache miss.
- The viewer protocol policy (allow HTTP, redirect HTTP to HTTPS, or HTTPS only).
- The allowed HTTP methods, such as
GET, HEADonly. - The cache policy, which sets TTLs and what goes into the cache key.
- Optional origin request and response headers policies.
- Whether CloudFront compresses responses.
- Whether viewers must use signed URLs or signed cookies.
Every distribution has a default behavior with the pattern *. It cannot be deleted and it always has the lowest precedence. Any request that matches no other pattern uses it. You add further behaviors only when some paths need different rules.
Why split paths into behaviors
A static site usually contains two kinds of content:
- HTML pages, whose names never change and which should become fresh within minutes.
- Fingerprinted assets such as
app.4f9c1e.js, whose names change when the content changes and which can be cached for a year.
One set of cache settings cannot suit both. Behaviors let you give /assets/* a long lifetime and leave the default behavior with a short one. You can also point a behavior at a different origin, such as a second bucket for user uploads. Both origins can sit behind the same domain name.
How path patterns match
A path pattern is compared only with the path portion of the URL. Query strings are never part of the match. The rules are:
- Matching is case-sensitive.
/Images/*does not match/images/logo.png. *matches zero or more characters, and that includes/. So*.jpgmatches/a/b/c.jpg.?matches exactly one character.- A pattern is at most 255 characters.
- A distribution has a quota on the number of behaviors. Check Service Quotas for the current value in your account.
| Pattern | Matches | Does not match |
|---|---|---|
| `assets/*` | `/assets/app.js`, `/assets/img/a.png` | `/assets` (no trailing path), `/Assets/app.js` |
| `*.jpg` | `/photo.jpg`, `/gallery/2024/photo.jpg` | `/photo.JPG`, `/photo.jpeg` |
| `img?/*` | `/img1/a.png`, `/imgA/a.png` | `/img/a.png`, `/img12/a.png` |
| `downloads/*.zip` | `/downloads/tool.zip` | `/downloads/tool.tar` |
| `*` | everything not matched earlier | nothing, it is the catch-all |
Use the same style for all patterns in one distribution. Write them either all with a leading slash or all without, so the list is easy to read and compare.
Precedence: first match wins
CloudFront evaluates behaviors in the order they are listed. The default behavior is always last. The first pattern that matches is used, and the rest are ignored. A broad pattern placed too early shadows the narrower ones below it.
Here is a common mistake. You define *.zip as the first behavior and downloads/*.zip second. The second pattern can never be reached, because every path it matches also matches the first. Put the most specific patterns first and the broadest last.
Matching paths to S3 keys
A path pattern selects a behavior. It does not rewrite the request. CloudFront forwards the full viewer path to the origin, so a request for /assets/app.js asks S3 for the key assets/app.js. Two consequences follow:
- Your bucket layout must mirror your URL layout. Put fingerprinted files under an
assets/prefix and theassets/*behavior will match them. - If a bucket stores everything under a prefix such as
site/, set the origin's Origin Path to/site. CloudFront then prepends it to every request. The pattern is still matched against the viewer path, without the prefix.
Because the bucket policy from the previous chapter names the distribution and not a behavior, it covers every behavior that uses that bucket. A second bucket as a second origin needs its own policy statement for the same distribution ARN.
A distribution with two behaviors
This excerpt extends the earlier distribution. The default behavior uses the managed CachingOptimized policy. The assets/* behavior is added first, with compression enabled. It reuses the earlier SiteOac and s3-origin definitions.
Resources:
SiteDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: true
DefaultRootObject: index.html
Origins:
- Id: s3-origin
DomainName: !GetAtt SiteBucket.RegionalDomainName
OriginAccessControlId: !GetAtt SiteOac.Id
S3OriginConfig:
OriginAccessIdentity: ''
CacheBehaviors:
- PathPattern: assets/*
TargetOriginId: s3-origin
ViewerProtocolPolicy: redirect-to-https
AllowedMethods: [GET, HEAD]
Compress: true
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6
DefaultCacheBehavior:
TargetOriginId: s3-origin
ViewerProtocolPolicy: redirect-to-https
AllowedMethods: [GET, HEAD]
Compress: true
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39adThe 4135ea2d-... ID is the managed CachingDisabled policy, and 658327ea-... is CachingOptimized. Using CachingDisabled on the default behavior makes HTML always fetch from S3. That is safe for testing but sends every page view to the origin. For production, prefer a custom cache policy with a short TTL (the next chapters cover cache policies and TTLs). The two behaviors here differ only in their cache policy, which is the common pattern.
Verifying which behavior applied
CloudFront adds an X-Cache header to responses. Request the same file twice and compare:
curl -sI https://dxxxxxxxxxxxx.cloudfront.net/assets/app.4f9c1e.js | grep -i -E "x-cache|cache-control|content-encoding"
curl -sI https://dxxxxxxxxxxxx.cloudfront.net/assets/app.4f9c1e.js | grep -i -E "x-cache|age"The first call normally shows Miss from cloudfront and the second Hit from cloudfront, with an Age header giving the seconds since the object was cached. The hit may land on a different edge location than the miss. If you always see misses on a path that should cache, the usual causes are:
- The request matched a different behavior than you expected, often because of pattern order or case.
- The origin sent
Cache-Control: no-storeorprivate, and the cache policy honors it. - The cache key includes something that varies per request, such as a query string or cookie.
To find out which behavior matched, give each one a visible difference, such as a custom response header from a response headers policy, or check the distribution configuration with aws cloudfront get-distribution-config.
Changing behaviors safely
- Edits to a distribution take a few minutes to deploy to all edge locations. The distribution status shows
InProgressuntil then. - A change to a behavior does not remove objects already cached. Edge locations may keep serving them until their TTL expires, so invalidate paths if you need an immediate change.
- Restricting methods with
AllowedMethods: [GET, HEAD]is a cheap safeguard for a read-only static site. Without it, a behavior configured for all methods will forwardPUTorDELETErequests to S3. The OAC-signed request would be refused unless the bucket policy allowed it, but you still pay for the round trip. - Adding a behavior for a new prefix does not require S3 changes. Only the bucket layout and the policy matter.
Summary of decision criteria
| Situation | Approach |
|---|---|
| Content types with different freshness needs | One behavior per path prefix, each with its own cache policy |
| Different backends on one domain | One origin per backend, one behavior per prefix |
| Restricted downloads | A dedicated behavior requiring signed URLs |
| Everything behaves the same | Use only the default behavior |
Exercise
A distribution has these behaviors in order: *.js (cache 1 hour), assets/* (cache 1 year), and the default *. A viewer requests /assets/app.4f9c1e.js. Which behavior applies, and what would you change so the file is cached for a year?
Show answer
The *.js behavior applies, because it is first in the list and * matches the / characters in the path. The one-hour policy therefore wins. Move assets/* above *.js so the more specific pattern is evaluated first. Then /assets/app.4f9c1e.js uses the one-year policy, and other .js files still use the one-hour policy.
Exercise
Your behavior pattern is Images/*, but viewers request /images/logo.png and get the default behavior's settings. Why, and how do you fix it?
Show answer
Path patterns are case-sensitive, so Images/* does not match /images/logo.png. Change the pattern to images/*, or to match the real casing of your keys and URLs. Wait for the distribution to finish deploying. Then verify with curl -I and the X-Cache and Cache-Control headers.