Sub topic 1
How a CDN and Edge Caching Work
Prerequisites
This chapter assumes you understand S3 buckets, objects, and keys; basic HTTP requests and status codes; IAM policy structure; and AWS CLI commands.
How a CDN and Edge Caching Work
A content delivery network (CDN) serves content from geographically distributed edge locations. CloudFront receives a viewer request at a nearby edge location. If the requested object is cached there, CloudFront returns it without contacting S3. This is a cache hit. Otherwise, CloudFront requests the object from its origin, stores the response according to its cache settings, and returns it. This is a cache miss.
Using an S3 Bucket as an Origin
An origin is the backend from which CloudFront fetches content. For S3, objects are addressed by bucket name and object key. CloudFront can serve HTML, JavaScript, images, downloads, and other S3 objects through one distribution.
CloudFront uses the S3 bucket’s regional REST endpoint for a private origin. The distribution then becomes the public entry point while the bucket remains inaccessible to ordinary public requests.
Choosing the REST Endpoint or the Website Endpoint
Use the S3 REST endpoint when CloudFront should access a private bucket with Origin Access Control (OAC). It supports CloudFront’s signed requests and normal S3 authorization.
Use the S3 website endpoint when you need S3 website-hosting behavior, such as S3 redirects or its built-in error documents. It requires a public website endpoint and cannot use OAC. For most CloudFront-backed sites, the REST endpoint is the safer default.
> callout note > Do not enable public read access merely to make CloudFront work. Configure OAC and a bucket policy instead. > ```
Creating a CloudFront Distribution
A distribution connects viewers, cache behaviors, and one or more origins. Set the S3 regional domain name as the origin, choose a cache policy, set a default root object such as index.html, and redirect HTTP viewers to HTTPS. CloudFront takes time to deploy changes globally.
Keeping the Bucket Private with Origin Access Control
OAC makes CloudFront sign origin requests with Signature Version 4. The bucket policy grants s3:GetObject only to CloudFront and only for the intended distribution:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "cloudfront.amazonaws.com"},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example-site/*",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/EDFDVBD6EXAMPLE"
}
}
}]
}Keep S3 Block Public Access enabled. Test the CloudFront URL, then confirm a direct unauthenticated S3 request is denied.
Exercise
A viewer requests an object that is not cached at the nearest edge. What happens next?
Show answer
CloudFront requests the object from the S3 origin, returns it to the viewer, and caches the response according to the distribution’s settings.