Sub topic 10
Default root object and custom error pages
This chapter covers two settings that decide what a visitor sees when the URL does not name a file, or names a file that does not exist. The first is the default root object. The second is custom error responses. Both belong to the distribution itself, so they apply to every cache behavior.
It assumes you can already create a distribution with an S3 origin protected by Origin Access Control (OAC), read a bucket policy, and run AWS CLI and curl commands. It also assumes you know the HTTP status codes 200, 403, and 404.
The default root object
A viewer who requests https://d111111abcdef8.cloudfront.net/ sends the path /. S3 stores objects by key, and no object has the key /. Without help, S3 would return an error or a bucket listing. The default root object is a file name you set on the distribution. When the request path is exactly /, CloudFront rewrites it to that object before it contacts the origin.
In CloudFormation it is one line, as in the distribution from the earlier chapter:
DistributionConfig:
Enabled: true
DefaultRootObject: index.htmlSet it as index.html with no leading slash. The value is a plain object key.
What it does not do
The default root object applies only to the root of the distribution. It does not apply to subdirectories. A request for /docs/ is not rewritten to /docs/index.html. CloudFront forwards the key docs/ to S3, and S3 has no such object, so you get an error.
This surprises people who have used web servers such as Apache or Nginx. Those servers map a directory to its index file. S3 has no real directories. The "folder" docs/ is only a shared key prefix.
You have three ways to handle subdirectory index pages:
| Approach | How it works | Trade-off |
|---|---|---|
| Link to full file names | Use `/docs/index.html` everywhere | Ugly URLs, and old links break |
| CloudFront Function | Rewrite the URI on each viewer request | Small code to maintain, a small per-request cost |
| S3 website endpoint | S3 applies its index document in every folder | The bucket must be publicly readable, and OAC cannot be used |
For a private bucket behind OAC, the CloudFront Function is the usual choice. The next section shows one.
Rewriting subdirectory requests with a CloudFront Function
A CloudFront Function runs at the edge on each viewer request, before the cache lookup. The following function appends index.html to paths that end in a slash. It also appends /index.html to paths whose last segment has no dot.
function handler(event) {
var request = event.request;
var uri = request.uri;
if (uri.charAt(uri.length - 1) === '/') {
request.uri = uri + 'index.html';
} else {
var lastSegment = uri.substring(uri.lastIndexOf('/') + 1);
if (lastSegment.indexOf('.') === -1) {
request.uri = uri + '/index.html';
}
}
return request;
}You attach the function to the viewer request event of the cache behavior. Because the rewrite happens before the cache lookup, the cache key uses the rewritten path. /docs and /docs/ therefore share one cache entry.
Why a missing object returns 403
Request a file that does not exist from a private bucket behind OAC, and you will often get 403 Forbidden instead of 404 Not Found. This is not a CloudFront bug. S3 hides whether a key exists from callers who may not list the bucket. If the caller has s3:GetObject but not s3:ListBucket, S3 answers 403 for a missing key.
The bucket policy from the earlier chapter grants only s3:GetObject. If you want real 404 responses, add a second statement that lets the same distribution list the bucket:
{
"Sid": "AllowCloudFrontServicePrincipalList",
"Effect": "Allow",
"Principal": {
"Service": "cloudfront.amazonaws.com"
},
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::amzn-s3-demo-bucket",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/EDFDVBD6EXAMPLE"
}
}
}Add this statement to the existing Statement array. Note that the Resource has no /*. s3:ListBucket applies to the bucket, while s3:GetObject applies to objects.
Granting list permission does not let viewers list your bucket. CloudFront only fetches the keys viewers ask for. Whether to grant it is a design choice. Some teams prefer 403 because it reveals nothing about which keys exist. Other teams want accurate 404 responses for monitoring. Whichever you choose, plan the custom error responses below for both codes.
Custom error responses
A custom error response tells CloudFront what to return when the origin answers with a given error status. Each rule has four settings:
- HTTP error code. The status from the origin that triggers the rule, such as 403 or 404. CloudFront supports a fixed list of codes, including 400, 403, 404, 405, 414, 416, 500, 501, 502, 503, and 504.
- Response page path. The path of the page to show, such as
/errors/404.html. CloudFront fetches this page from the origin like any other request. - HTTP response code. The status that the viewer receives. It can differ from the origin's status.
- Error caching minimum TTL. The minimum number of seconds CloudFront caches the error. The default is 10 seconds.
Here is a rule set for a static site with a branded error page:
DistributionConfig:
DefaultRootObject: index.html
CustomErrorResponses:
- ErrorCode: 403
ResponseCode: 404
ResponsePagePath: /errors/404.html
ErrorCachingMinTTL: 60
- ErrorCode: 404
ResponseCode: 404
ResponsePagePath: /errors/404.html
ErrorCachingMinTTL: 60The first rule turns the 403 that S3 returns for missing keys into a 404 for the viewer. The second handles real 404 responses if you granted s3:ListBucket. Both show the same page.
Rules to remember
- The error page must exist in the bucket, and CloudFront must be allowed to fetch it. If the page itself fails, the viewer gets the raw error.
- Error rules are per distribution, not per behavior. A 404 from an API path and a 404 from the website path both get the same rule. If your distribution has several behaviors, this matters.
- The viewer's HTTP response code is your choice. Returning 200 for an error hides it from monitors, crawlers, and browsers.
Single-page applications
A single-page app (SPA) with client-side routing has one real file, index.html. A request for /profile/42 matches no key, so S3 returns 403 or 404. The common fix maps both errors to /index.html with a 200 response, so the app's router can handle the path:
CustomErrorResponses:
- ErrorCode: 403
ResponseCode: 200
ResponsePagePath: /index.html
ErrorCachingMinTTL: 0
- ErrorCode: 404
ResponseCode: 200
ResponsePagePath: /index.html
ErrorCachingMinTTL: 0This works, but it has costs. A missing image or script also receives index.html with status 200, which makes broken links hard to find. Search engines may index pages that do not exist. If the site mixes an SPA and static assets, consider limiting the damage with a separate distribution or a function that rewrites only extensionless paths.
Error caching
CloudFront caches error responses for the error caching minimum TTL, so the origin is not hit repeatedly for the same failing request. This protects the origin but can prolong an outage. Suppose you upload a missing file right after viewers requested it. With a 300-second error TTL, some viewers keep receiving the error for up to five minutes. For files that you may publish shortly after a miss, use a short value. Setting 0 turns minimum error caching off for that code.
Verifying the setup
Use curl to check each case against your distribution:
curl -I https://d111111abcdef8.cloudfront.net/
curl -I https://d111111abcdef8.cloudfront.net/docs/
curl -I https://d111111abcdef8.cloudfront.net/no-such-pageCheck these things in the output:
- The first request returns 200 with the content type of
index.html. - The second returns 200 only if you attached the rewrite function. Otherwise expect an error.
- The third returns the status you configured, and the
x-cacheheader showsError from cloudfrontorMiss from cloudfronton the first request.
After you change error rules or the default root object, the distribution status becomes InProgress until the change reaches all edge locations. Wait for Deployed before you test.
Common mistakes
| Symptom | Likely cause |
|---|---|
| `/` works but `/about/` fails | The default root object only covers `/`. Add a rewrite function. |
| Missing files return 403 | The bucket policy has no `s3:ListBucket`. Map 403 to a 404 page, or grant list access. |
| Custom error page itself returns an error | The page key is wrong, or the path pattern of the matching behavior does not reach it. |
| Broken assets return 200 HTML in an SPA | The 404-to-200 rule applies to every path. Narrow it. |
| Fixed file still shows an error | The error caching minimum TTL has not expired. |
Exercise
Your distribution uses a private bucket with OAC and the default root object index.html. Visitors to / see your home page, but /blog/ returns 403. Give two ways to fix it, and say why the S3 website endpoint is not a good fix here.
Show answer
The default root object applies only to /, so /blog/ is requested from S3 as the key blog/, which does not exist. You can fix it by attaching a viewer request CloudFront Function that rewrites /blog/ to /blog/index.html, or by changing links to point to /blog/index.html directly. The website endpoint applies index documents in every folder, but it requires a publicly readable bucket and does not support OAC, so it would give up the private-bucket setup.
Exercise
You add custom error rules for 403 and 404 that return /errors/404.html with status 404 and an error caching minimum TTL of 300 seconds. A viewer requests /new-report.pdf before you upload it, then you upload it a minute later. What happens, and what would you change?
Show answer
CloudFront caches the error for the TTL, so viewers can keep receiving the 404 page for up to five minutes even though the file now exists. Lower the error caching minimum TTL, for example to 10 or 0 seconds, or create an invalidation for /new-report.pdf after uploading.