Sub topic 2
Writing the bucket policy that trusts your distribution
Assume you know S3 buckets, HTTP requests, IAM policies, and basic AWS CLI use. This chapter focuses on how CloudFront access and caching work together.
Trusting CloudFront with a bucket policy
Keep the S3 bucket private. CloudFront uses an Origin Access Control (OAC) to sign requests to S3 with AWS Signature Version 4. The bucket policy trusts the CloudFront service only when the request comes from your distribution.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCloudFrontReadOnly",
"Effect": "Allow",
"Principal": {
"Service": "cloudfront.amazonaws.com"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/EDFDVBD6EXAMPLE"
}
}
}
]
}Replace the bucket name and distribution ARN. The /* applies to objects inside the bucket. This policy does not allow listing the bucket or uploading objects. Keep S3 Block Public Access enabled.
> callout note > The bucket policy must name the distribution that should access the bucket. Trusting the CloudFront service without the AWS:SourceArn condition grants broader access than necessary.
Cache behaviors and path patterns
A cache behavior matches request paths to an origin and caching rules. The default behavior matches every path unless a more specific pattern matches first.
For example, /assets/* can use long-lived caching, while /api/* can use a separate origin or a short time to live (TTL). CloudFront evaluates specific path patterns before the default behavior.
Cache policies and cache keys
A cache policy controls which request values form the cache key. The key normally includes the path. It can also include selected query strings, headers, and cookies.
Include a value only when it changes the response. Including unnecessary values creates separate cache entries and lowers the cache hit ratio.
| Request value | Typical choice |
|---|---|
| `?language=en` | Include when it changes the content |
Controlling freshness
A TTL controls how long CloudFront can reuse an object before checking the origin. The cache policy sets minimum, default, and maximum TTLs. The origin can further guide freshness with a Cache-Control header.
Fingerprint assets such as app.4f91.js can use a long lifetime:
aws s3 cp ./dist s3://amzn-s3-demo-bucket/assets/ --recursive \
--cache-control "public,max-age=31536000,immutable"Use shorter TTLs for frequently changing HTML. Publish a new fingerprinted filename when an asset changes instead of invalidating every cached copy.
Exercise
Why should a cache policy avoid including every request header in the cache key?
Show answer
Each distinct header value can create another cache entry, reducing cache hits and increasing origin requests.