Sub topic 2
Using an S3 bucket as an origin
This chapter assumes you know basic S3 concepts (buckets, objects, keys), can read HTTP status codes, and can run AWS CLI commands. Earlier chapters covered how a CDN caches content at edge locations. This chapter covers what CloudFront needs from the bucket behind it. Choosing between the two S3 endpoint types and wiring up access control come in the next chapters.
What an origin is
An origin is the server CloudFront asks when it does not have a fresh copy of an object. CloudFront can use many kinds of origins, such as load balancers, HTTP servers, and S3 buckets. S3 is a common choice for static sites, downloads, images, and video segments because it stores objects durably and needs no servers to manage.
The origin is part of a distribution's configuration. A distribution can have several origins, and cache behaviors (covered later) decide which origin handles which URL path.
The request flow on a cache miss
A viewer never talks to S3 directly in a well-built setup. The viewer talks to an edge location. The edge location talks to S3 only when it cannot answer from its cache.
Two details matter here:
- CloudFront forwards the URL path to S3 as the object key. A viewer request for
/img/logo.pngbecomes a request for the keyimg/logo.png. - S3 sends its response headers (such as
Content-Type,ETag, andCache-Control) back through CloudFront. CloudFront usesCache-Controlto decide how long to keep the object, which a later chapter covers.
Mapping URLs to object keys
S3 has no real folders. The key img/logo.png is one flat string, and the console only shows a folder view by splitting on /. This causes several behaviors you need to plan for:
- Keys are case-sensitive.
/Logo.pngand/logo.pngare different objects, and so are their cache entries. - There is no directory index. A request for
/docs/asks for the keydocs/, which usually does not exist. CloudFront's default root object only applies to the root URL/, not to subdirectories. The chapter on root objects and error pages covers this. - Special characters need URL encoding. A key with a space must be requested as
%20. Keep keys to lowercase letters, digits, hyphens, and slashes to avoid surprises. - Query strings are not used by S3. S3 ignores
?v=2when it picks the object. Whether CloudFront includes the query string in its cache key is a cache policy decision, so a query string can create separate cache entries for the same object.
Origin path
If your site files live under a prefix, set an origin path on the origin, for example /site. CloudFront prepends it to every request. A viewer request for /index.html then fetches the key site/index.html. This lets one bucket hold several sites or environments, each under its own prefix and each served by its own distribution.
Write the origin path with a leading slash and no trailing slash.
Which domain name to give CloudFront
When you add an S3 bucket as an origin, you give CloudFront a domain name for it. For a bucket accessed through the S3 REST API, use the bucket's regional domain name:
amzn-s3-demo-bucket.s3.us-east-1.amazonaws.comThe pattern is <bucket>.s3.<region>.amazonaws.com. In CloudFormation, !GetAtt SiteBucket.RegionalDomainName returns this value.
Avoid the older global name <bucket>.s3.amazonaws.com. For a newly created bucket outside us-east-1, DNS for the global name can take a while to point to the right region. During that time S3 answers with an HTTP 307 redirect to the regional name. CloudFront does not follow origin redirects to a different host for you in a useful way, so viewers can see errors or redirects to the bucket URL. The regional name avoids the problem.
The bucket can be in any region. CloudFront is global, and the edge locations fetch from the bucket's region. Data transfer from S3 to CloudFront is not charged. Requests that CloudFront makes to S3 are billed as normal S3 requests, and each cache hit avoids one of them.
Preparing a private bucket
The goal for a production setup is a bucket that is not reachable from the internet except through your distribution. Start with a bucket that has all four Block Public Access settings turned on. The following commands create one, upload a test page, and confirm that direct access fails.
aws s3api create-bucket \
--bucket amzn-s3-demo-bucket \
--region us-east-1
aws s3api put-public-access-block \
--bucket amzn-s3-demo-bucket \
--public-access-block-configuration \
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
echo '<h1>Hello from S3</h1>' > index.html
aws s3 cp index.html s3://amzn-s3-demo-bucket/index.html --content-type text/html
curl -I https://amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com/index.htmlFor any region other than us-east-1, create-bucket also needs --create-bucket-configuration LocationConstraint=<region>.
The curl command should print HTTP/1.1 403 Forbidden. That result is correct for now. The bucket has no policy that lets anyone read it, and the upcoming chapters add the one that lets only your distribution read it.
The same bucket in CloudFormation looks like this. It is the SiteBucket that the distribution template in a later chapter refers to.
Resources:
SiteBucket:
Type: AWS::S3::Bucket
Properties:
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
Outputs:
OriginDomainName:
Value: !GetAtt SiteBucket.RegionalDomainNameEncryption on the origin
Objects encrypted with SSE-S3 (AES256), as in the template above, need nothing extra. S3 decrypts them when CloudFront reads them.
Objects encrypted with SSE-KMS need one more step. The KMS key policy must allow the CloudFront service principal to use the key for decryption, scoped to your distribution. Without it, every cache miss fails with a 403, even though the bucket policy is correct. Customer-provided keys (SSE-C) do not work with CloudFront.
Missing objects: 403 or 404
A request for a key that does not exist produces different status codes depending on the permissions CloudFront has:
- If the caller has
s3:ListBucketon the bucket, S3 returns 404 Not Found. - If the caller has only
s3:GetObject, S3 returns 403 Forbidden, so that callers cannot discover which keys exist.
A private-bucket setup normally grants only s3:GetObject, so missing files appear as 403. A broken link and a permissions problem therefore look identical to a viewer. Keep this in mind when you read error rates in monitoring, and when you set up custom error responses to show a friendly 404 page. CloudFront can map both 403 and 404 to the same page.
Common errors
| Symptom | Likely cause | What to check |
|---|---|---|
| 403 `AccessDenied` for every object | No bucket policy for the distribution, or the policy names the wrong distribution ARN | Bucket policy `AWS:SourceArn` and the account ID |
| 403 for some objects only | Missing key (no `s3:ListBucket`), different key case, or SSE-KMS key access | Exact key in S3, and the KMS key policy |
| 307 redirect to the S3 hostname | Global bucket domain name used on a new bucket | Switch the origin to the regional domain name |
| Site works at `/` but not at `/docs/` | S3 has no directory index | Request `/docs/index.html` or handle it as covered in the root object chapter |
| Old file still served after upload | The edge location is serving a cached copy | TTL and invalidation, covered in later chapters |
Checking which path a request took
CloudFront adds response headers that help you debug origin behavior. After the distribution exists, run curl -I against it and read these:
X-Cache: Miss from cloudfrontmeans the edge fetched from S3.Hit from cloudfrontmeans it answered from the cache.X-Amz-Cf-Popnames the edge location that served you.Ageshows how many seconds the object has been in the cache.
Run the same request twice. The first normally shows a miss and the second a hit, which confirms that S3 is being used as a cached origin.
Exercise
A teammate reports that https://dxxxx.cloudfront.net/about/ returns 403, while https://dxxxx.cloudfront.net/about/index.html works. The bucket policy grants only s3:GetObject to the distribution. Why does the first request fail, and what status would you expect if the bucket policy also granted s3:ListBucket?
Show answer
CloudFront asks S3 for the key about/, which does not exist, because S3 has no directory index and the default root object applies only to /. With only s3:GetObject, S3 hides whether a key exists and returns 403. With s3:ListBucket as well, S3 would return 404 for the missing key. The fix is to link to /about/index.html or add rewrite handling for directory paths.
Exercise
You create a bucket in eu-west-1 and use amzn-s3-demo-bucket.s3.amazonaws.com as the origin. Some viewers get redirected to an S3 URL. What is happening, and what should you change?
Show answer
The global name can return an HTTP 307 redirect to the regional endpoint while DNS for a new bucket outside us-east-1 is still propagating. Change the origin domain name to the regional name, amzn-s3-demo-bucket.s3.eu-west-1.amazonaws.com.