Sub topic 3
Serving S3 Content Through Amazon CloudFront
Assume you know S3 buckets and objects, HTTP status codes, IAM policies, and basic AWS CLI commands. This chapter focuses on the publishing and delivery settings that complete an S3-backed CloudFront distribution.
Root objects and error pages
Set DefaultRootObject to index.html so a request for / retrieves that object. CloudFront does not automatically interpret S3 folders as web pages.
Configure custom error responses for statuses such as 403 and 404. A private S3 origin often returns 403 when an object is missing. You can map that response to /error.html, set the viewer status to 404, and choose a short error-cache time.
DefaultRootObject: index.html
CustomErrorResponses:
- ErrorCode: 403
ResponsePagePath: /error.html
ResponseCode: 404
ErrorCachingMinTTL: 10Publishing updates
Use versioned file names for assets that change rarely. For example, publish app.8f31c.js instead of replacing app.js. The new key creates a new cache entry and avoids an invalidation.
Use an invalidation when a stable path must change immediately, such as /index.html.
aws cloudfront create-invalidation \
--distribution-id EDFDVBD6EXAMPLE \
--paths "/index.html" "/css/*"Invalidations add operational cost after the included allowance and take time to propagate. Versioned names usually scale better for static assets.
Custom domains and HTTPS
Request an ACM certificate for www.example.com in us-east-1, even if the distribution uses another AWS Region. Validate domain ownership with DNS, then attach the certificate and an alternate domain name to the distribution. Create a DNS alias from the hostname to the distribution domain name, and set the viewer protocol policy to redirect HTTP to HTTPS.
Response headers
A response headers policy adds headers without changing objects in S3. Use one to set security headers such as Strict-Transport-Security and Content-Security-Policy, or CORS headers for approved application origins. Avoid allowing every origin when the content is private.
Signed private content
Signed URLs authorize one object for a limited time. Signed cookies authorize multiple objects, which suits protected downloads or a private application area. CloudFront verifies the signature and expiration before serving a cached object. The S3 bucket policy should still allow reads only from CloudFront through OAC.
Monitoring and cost
Track cache hit ratio, requests, bytes transferred, 4xx and 5xx responses, and invalidation counts in CloudFront metrics. A low hit ratio can increase S3 requests and data-transfer costs. Narrow cache keys, suitable TTLs, compression, and versioned assets reduce repeated origin fetches.
Exercise
Which publishing method is usually best for a changed JavaScript bundle?
Show answer
Upload it under a new fingerprinted file name and update the HTML reference.