Sub topic 4
Creating a CloudFront distribution
A distribution is the top-level CloudFront resource. It ties together the origins CloudFront fetches from, the cache behaviors that decide how each request is handled, and the domain name viewers use. This chapter walks through creating one that fronts an S3 bucket and explains the settings that matter most.
Prerequisites
This chapter assumes you already know the following:
- S3 buckets, objects, and keys, and the difference between the S3 REST endpoint and the website endpoint (covered in the previous chapter).
- HTTP requests, responses, and status codes.
- How to read a JSON policy and run AWS CLI commands.
The Origin Access Control (OAC) resource appears in the examples here. The next chapter explains how it works and the bucket policy that goes with it.
What a distribution contains
A distribution has a small number of parts. Each one answers a different question.
| Part | Question it answers | Example in this chapter |
|---|---|---|
| Origin | Where does CloudFront get the content on a cache miss? | The S3 bucket's regional domain name |
| Default cache behavior | How are requests handled when no other path pattern matches? | HTTPS redirect and the CachingOptimized policy |
| Default root object | What is served for a request to `/`? | `index.html` |
| Domain name | What hostname do viewers use? | The generated `dxxxx.cloudfront.net` name |
| Price class and status | Which edge locations are used, and is the distribution live? | `Enabled: true` |
CloudFront assigns every distribution an ID (for example EDFDVBD6EXAMPLE) and a domain name of the form d111111abcdef8.cloudfront.net. You can use that domain name to test before you attach a custom domain.
The request flow
When a viewer requests a file, the request goes to a nearby edge location. The edge checks its cache. On a hit, it answers immediately. On a miss, it goes to the origin, stores the response according to the cache policy, and returns it to the viewer.
Choosing the origin domain name
The origin's domain name is the first setting that causes errors. For a private bucket, use the bucket's regional REST endpoint, in the form amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com. In CloudFormation, !GetAtt SiteBucket.RegionalDomainName returns exactly this value.
Avoid the global name amzn-s3-demo-bucket.s3.amazonaws.com for new buckets. For a short time after bucket creation, the global name can answer with a temporary redirect to the regional name. CloudFront does not follow that redirect for the viewer's benefit, and viewers can see errors or be sent to the bucket directly.
Do not use the website endpoint (...s3-website-us-east-1.amazonaws.com) if you want Origin Access Control. OAC works only with the REST endpoint. The website endpoint is a public HTTP-only endpoint, and CloudFront treats it as a custom origin.
Create the distribution with CloudFormation
The following excerpt defines an OAC and a distribution. It assumes the bucket SiteBucket is defined elsewhere in the same template.
Resources:
SiteOac:
Type: AWS::CloudFront::OriginAccessControl
Properties:
OriginAccessControlConfig:
Name: site-oac
OriginAccessControlOriginType: s3
SigningBehavior: always
SigningProtocol: sigv4
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: ''
DefaultCacheBehavior:
TargetOriginId: s3-origin
ViewerProtocolPolicy: redirect-to-https
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6Read the template from the top down.
SiteOacis the Origin Access Control.SigningBehavior: alwaysmakes CloudFront sign every request it sends to S3 with Signature Version 4 (SigV4).DefaultRootObjectis the object CloudFront returns for a request to the distribution's root, such ashttps://d111111abcdef8.cloudfront.net/. Write the value without a leading slash.Originslists each origin with a localId. TheIdis only a label that behaviors use to refer to the origin.OriginAccessControlIdattaches the OAC to the origin.S3OriginConfigwith an emptyOriginAccessIdentitymarks this as an S3 origin that does not use the older Origin Access Identity (OAI). The empty string is required by the schema when you use OAC.DefaultCacheBehaviorapplies to every request that no other path pattern matches.TargetOriginIdmust match an originId.ViewerProtocolPolicy: redirect-to-httpsanswers plain HTTP requests with a redirect to HTTPS.CachePolicyIdis the ID of the AWS managed policy CachingOptimized. Later chapters cover cache policies in detail.
Deployment and status
A new or changed distribution has the status InProgress while CloudFront pushes the configuration to its edge locations. It changes to Deployed when that finishes, which usually takes a few minutes. You can use the CLI to wait for it:
aws cloudfront wait distribution-deployed --id EDFDVBD6EXAMPLEYou can then test with the generated domain name:
curl -I https://d111111abcdef8.cloudfront.net/The response headers show whether the cache was used. Look for X-Cache, whose value is Miss from cloudfront on the first request and Hit from cloudfront on a repeat. The Age header shows how many seconds the object has been in the edge cache.
Settings you will meet in the console
The console wizard exposes more options than the template above. These are the ones worth understanding now.
Price class
The price class limits which edge locations serve your traffic. All locations give the lowest latency worldwide. The lower-cost classes exclude the most expensive regions, so viewers in those regions are served from a farther location. Choose a lower class if your audience is concentrated in a few regions.
HTTP versions and IPv6
Distributions support HTTP/2 by default, and you can enable HTTP/3. IPv6 is enabled by default. If you create an alias record for a custom domain, create both A and AAAA records, or IPv6 viewers cannot reach the distribution by that name.
Allowed HTTP methods
The default allows only GET and HEAD. That is correct for static sites. OPTIONS is needed only when CORS preflight requests must be cached or answered by the origin. Methods such as PUT and POST turn the distribution into an upload path. That is a different design with additional signing requirements, so leave it alone for a read-only site.
Compression
CloudFront can compress text content such as HTML, CSS, and JavaScript with gzip and Brotli when the cache policy enables those encodings and the viewer sends an Accept-Encoding header. CachingOptimized enables both. Objects smaller than about 1 KB, or larger than about 10 MB, are not compressed.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `403 AccessDenied` XML from S3 | The bucket policy is missing or names the wrong distribution ARN | Add the policy from the next chapter and check the ARN |
| `403` for `/` but not for `/index.html` | `DefaultRootObject` is not set | Set it, then wait for `Deployed` |
| `404` or `403` for a path like `/docs/` | The default root object applies only at the root, not to subdirectories | Request the full key, or rewrite the path at the edge |
| Browser downloads a redirect loop or shows an odd page | The origin is the website endpoint with the wrong protocol setting | Use the REST endpoint with OAC, or set the website origin to HTTP only |
| Changes in S3 do not appear | The old object is still cached | Wait for the TTL to expire, or see the chapter on invalidations and versioned names |
| Stack update fails on the origin | The origin `Id` or the OAC was changed in a way that leaves a behavior pointing at a missing origin | Update behaviors and origins in the same change |
Check the result from the CLI
Use the CLI to confirm what was created. The query below prints the distribution's domain name and status.
aws cloudfront get-distribution \
--id EDFDVBD6EXAMPLE \
--query "Distribution.[DomainName,Status]" \
--output textTo see the origin and the behavior CloudFront stored, request the full configuration:
aws cloudfront get-distribution-config --id EDFDVBD6EXAMPLEThe response includes an ETag. To update a distribution from the CLI, you must pass that value as --if-match. This guards against two people overwriting each other's changes. CloudFormation handles this for you.
Design decisions to settle early
- One distribution or several. A single distribution can serve many paths through cache behaviors. Use separate distributions only when you need different domain names, certificates, or logging destinations.
- Infrastructure as code. Distribution settings are easy to change by hand and hard to remember. Keep the definition in a template so changes are reviewed and repeatable.
- Origin Access Control from the start. Adding OAC later means changing the bucket policy and Block Public Access at the same time as a live distribution. Starting private avoids that.
Exercise
A new distribution with an S3 REST endpoint origin returns 403 for every request, including /index.html, although its status is Deployed. Name the most likely cause and the fix.
Show answer
The bucket has no policy that allows the distribution to read objects. OAC makes CloudFront sign requests, but S3 still needs a bucket policy that allows s3:GetObject for the cloudfront.amazonaws.com service principal, with an AWS:SourceArn condition naming the distribution's ARN. Add that policy (or correct a wrong ARN) and test again.
Exercise
Why does the template set S3OriginConfig.OriginAccessIdentity to an empty string, and what would change if you pointed the origin at the bucket's website endpoint instead?
Show answer
The empty string tells CloudFront this is an S3 origin that does not use the legacy Origin Access Identity, so access is controlled by the OAC referenced in OriginAccessControlId. A website endpoint is a public HTTP-only custom origin. It cannot use OAC, so the bucket would need public read access, and CloudFront-to-origin traffic would not be encrypted.