ARTICLE - CDN Acceleration

AWS CloudFront Setup Guide: Distributions & Caching

The hard part of CloudFront is not getting a distribution to work but six decisions: how origins connect, how the cache key is defined, which TTL wins, where the certificate lives, invalidation versus versioned filenames, and how to read logs and costs. This guide reorders the setup around those six decisions and closes with three common misconfigurations plus a checklist.

2026-08-06 AWS Documentation

AWS CloudFront Setup Guide: Distributions & Caching

CloudFront is Amazon Web Services' global content delivery network, native to the same platform as S3, EC2, ALB, and Route 53. Launched in 2008, it has long ranked among the top three CDN platforms, covering 600+ points of presence across 90+ cities in 135+ countries, including 300+ edge locations and 13 Regional Edge Caches. That two-tier cache means the layer nearest the origin aggregates origin fetches, which visibly reduces origin load.

What actually blocks newcomers was never "can it be configured at all". The console flow is documented clearly enough that twenty minutes of clicking yields a working domain. The hard part is the decisions that follow: which dimensions belong in the cache key, whose TTL wins, which region holds the certificate, and whether content updates rely on invalidation or on new filenames. Choose wrong here and the site still runs, but hit ratio, cost, and troubleshooting difficulty all degrade together.

This guide reorders the setup around six decisions: how origins connect, how the cache key is defined, how TTL priority works, where the certificate and domain go, invalidation versus versioning, and how to read logs and costs. Each chapter covers one decision, and the article closes with three common misconfigurations plus a checklist you can tick through. Configuration names and quotas follow the CloudFront Developer Guide; quotas, prices, and features change by region and release, so verify against the official docs before making changes.

1. Origins: Get the Type Right First

Origin type How to connect Must configure Typical failure Fits
S3 origin S3 bucket plus OAC Lowercase bucket name without spaces, no public read, OAC authorisation 403 or 404 (invalid bucket name, unauthorised) Static assets
Custom origin Domain or IP with origin protocol and port Explicit origin Host header, optional Origin Path such as /static 403 or 404 (Host missing), intermittent 504 (port not allowed) EC2, ALB, other clouds and self-hosted rooms
Origin group Primary plus secondary origin Primary/secondary assignment, failover status range, failback policy Still failing after the switch (security group blocks origin fetches) Multi-region deployments and regional failover

1.1 S3 origins and OAC

S3 is the least troublesome home for static assets. Bucket names must be lowercase without spaces, an S3 constraint that simply surfaces on the CloudFront creation page, but access control matters more: use Origin Access Control (OAC) so the bucket can only be reached through CloudFront, rather than opening the bucket for public reads.

The value of OAC is that signed requests replace the older combination of IP allowlists and Referer checks: edge locations fetch objects with an IAM signature, and the bucket policy trusts only that signature. Someone who learns the bucket domain still cannot pull content around the CDN. When reusing an old template, confirm the origin uses OAC rather than the superseded OAI.

Only after the origin is ready does distribution creation begin: name the distribution and attach up to 50 tags for resource grouping and cost allocation by project, environment, or team. Names and tags do not change distribution behavior, but adding tags after the bill arrives leaves past usage impossible to attribute.

1.2 Custom origins and load balancer origins

When the origin is not S3, connect it as a custom origin: enter the domain or IP, set the origin protocol and port, and optionally set an Origin Path such as /static so the CDN only fetches that directory. The origin host header must be set explicitly, otherwise virtual hosts on the origin fail to match and surface as 403 or 404 responses.

When the origin is EC2 or a self-hosted server, the security group must allow CloudFront origin fetches; when the origin is an ALB, use the ALB domain as the origin instead of pointing at backend instances, so health checks, connection reuse, and certificate management stay in the load balancer. For troubleshooting origin paths, see CDN origin fetch basics.

1.3 Origin groups and failover

A distribution can carry multiple origins in an origin group, failing over automatically when the primary becomes unavailable. That is the least-effort layer of resilience for multi-region deployments: primary origin is an S3 bucket in Singapore, secondary is an S3 bucket in Frankfurt, and CloudFront decides when to switch without any DNS manipulation.

Two things must be decided alongside the group: the status-code range that triggers failover, and the failback policy after switching. Configure switching without failback and traffic lingers on the secondary origin, dragging both cost and latency off target. The reasoning overlaps with multi-cloud resilience, which is covered in the resilience sections of our CDN provider comparison.

2. Cache Keys: The Easiest Thing to Get Wrong

2.1 What a cache key contains

A cache key decides which requests count as the same object. By default it includes only host and path, so /a.jpg and /b.jpg are two objects, while /a.jpg?x=1 and /a.jpg?x=2 are treated as the same object unless query strings enter the key.

Optional dimensions are query strings, headers, and cookies. Every dimension added multiplies the number of cache partitions: three query parameters with ten possible values each yield a thousand partitions. That single choice decides hit ratio, and it decides how many origin fetches the origin must absorb.

2.2 Too much kills hit ratio, too little serves wrong content

There are two failure directions, and they are symmetrical. Put in too much and hit ratio collapses: stuffing User-Agent, Accept-Language, and entire cookies into the key gives nearly every visitor a private partition, caching becomes decorative, and origin fetches explode.

Put in too little and content is wrong: a multilingual site that omits language hands English visitors Chinese pages, and a multi-tenant system that omits tenant identity lets customer A's page be served to customer B. The test is whether content varies with the dimension: if it does, include it; if not, leave it out. The systematic breakdown is in cache key strategy.

2.3 The three managed policies and where custom begins

CloudFront ships managed cache policies you can select per scenario: CachingOptimized sets long TTLs for static assets and ignores query strings (great for images, CSS, and JS); CachingDisabled never caches, which suits dynamic APIs and authenticated requests; Elemental-MediaPackage targets streaming.

When customizing, watch two fields: the TTL minimum, default, and maximum, which set how long objects stay at the edge, and the cache key, which sets the dimensions used to distinguish objects. Managed policies cover about eighty percent of cases, so write a custom policy for the remaining twenty percent instead of starting from zero, which is far steadier. General principles are in CDN cache strategy.

3. TTL and the Priority of Origin Cache Headers

3.1 TTL minimum, default, and maximum

Cache duration is decided by three values working together: minimum TTL, default TTL, and maximum TTL. The default applies when the origin sends no cache headers; the minimum and maximum clamp whatever the origin does send, preventing excessively short or long lifetimes.

In practice the common setup is: static assets get a default TTL of 30 days or more, the minimum TTL is not zero (otherwise an origin no-cache forces frequent refetches), and the maximum TTL caps things so a mistaken one-year header cannot freeze content indefinitely.

3.2 Who wins: origin Cache-Control or CloudFront settings

Priority is fixed: the origin's Cache-Control or Expires header wins, and the three CloudFront TTLs only clamp around it. If the origin says max-age=60, you get 60 seconds, unless 60 seconds falls outside the minimum or maximum and gets clamped.

That rule explains a frequent confusion: you change the distribution TTL and cache lifetime does not move, because the origin keeps sending its own cache headers. Either change the origin or override it with a cache policy that narrows the min/max window. Both work, but you need to know which layer you are editing.

4. Certificates and Domains

4.1 ACM certificates must live in us-east-1

CloudFront serves HTTPS on *.cloudfront.net by default. To use your own domain, request a certificate in AWS Certificate Manager (ACM), and the certificate must be created in us-east-1 (N. Virginia), a CloudFront requirement that runs against normal regional habits and is the usual reason a requested certificate cannot be selected.

Once issued, no private key download is needed because CloudFront references the ACM certificate directly. If an ALB also serves the site, each layer needs its own certificate: the ALB uses one in its own region and CloudFront uses one in us-east-1, and no single certificate spans both. For certificate types and validation methods, see CDN HTTPS configuration basics.

4.2 Alternate domain names and two ways to point DNS

Add the alternate domain name (CNAME), for example cdn.example.com, then point it at d111111abcdef8.cloudfront.net in DNS. There are two ways: an alias record when the hosted zone is on Route 53, or a plain CNAME at other DNS providers.

With a plain CNAME, remember that apex domains cannot be CNAMEs, so something like example.com needs a Route 53 alias or an A-record arrangement. After configuring, do not rush the DNS change: confirm the distribution status has moved from Deploying to Enabled, otherwise the moment resolution takes effect error pages appear and it is easy to misread as a certificate problem.

5. Invalidation or Versioned Filenames

5.1 Invalidation quotas and costs

After the origin changes, invalidation clears edge caches on demand. In the console, open the Invalidations page and enter object paths:

Object paths: /images/logo.png   (single file)
              /images/*          (wildcard, all images)
              /*                 (whole site)

The CLI suits release pipelines better, once the AWS CLI is installed and configured:

aws cloudfront create-invalidation \
  --distribution-id E123ABC456DEF7 \
  --paths "/images/*" "/index.html"

Remember the constraints: every invalidation request needs at least one path, the free allowance is 1,000 paths per month counted per path, and each additional path costs about $0.005. /* counts as a single path but empties every edge location. Invalidations usually complete within minutes, and frequent full-site purges not only cost money but also make hit ratio fall off a cliff during peak traffic.

5.2 Why versioned filenames are more reliable

Invalidation is a push model: content changed, so notify every cache layer to drop it. Versioned filenames are a pull model: content changed, so change the URL, for example style.v3.css, and the new URL is a guaranteed miss while the old object expires naturally at the edge.

Over the long run the second is more reliable: no quota consumed, no throttling risk, rollback by pointing references back, and a smooth hit-ratio curve. The cost is that the build must emit fingerprinted filenames and HTML references must be updated in step. The practical compromise is versioning for static assets, short TTLs for HTML and APIs plus targeted invalidation when needed; the division of labor is in the cache purging and preheating guide.

6. Logs, Metrics, and Cost Structure

6.1 Which logs and metrics to watch

Standard logs can be delivered to S3 and real-time logs can go through Kinesis; both support computing hit ratio, status-code distribution, and popular paths. On the metrics side, watch cache hit ratio, origin error rate (5xx), and time to first byte: a falling hit ratio usually means a misconfigured cache key or TTLs overridden by the origin, while rising origin 5xx usually means security groups, OAC, or the origin protocol.

Fix the troubleshooting order: confirm the distribution is Enabled, check the origin request headers Host and User-Agent, verify the origin security group allows CloudFront, and finally check OAC/OAI permissions. That sequence localizes most configuration errors within two passes.

6.2 Cost structure and price classes

CloudFront bills egress data transfer and requests separately: from us-east-1 to the internet, transfer starts around $0.085/GB, and HTTP requests run on the order of $0.01 per 10,000. Invalidation requests bill separately too, which is where the 1,000 free paths per month comes from.

The most direct cost control is the Price Class: if the site only serves specific regions, narrowing delivery to North America and Europe, or to Asia, saves a meaningful amount. S3 origins also qualify for a dedicated egress discount through CloudFront, which is the most tangible benefit of an origin inside AWS. For the broader cost model, see the conversion method in our cloud server price comparison.

7. Three Common Misconfigurations and a Checklist

7.1 Three misconfigurations, and where CloudFront fits

Misconfiguration one: putting every header except Accept-Encoding into the cache key. Accept-Encoding is required for compression negotiation, but User-Agent, Accept-Language, and whole cookie strings only create a partition disaster. Include only the dimensions that genuinely change content.

Misconfiguration two: long TTLs on HTML while relying on manual invalidation. Long TTLs and manual invalidation cancel each other out, and one forgotten invalidation means users see stale pages for a long time. HTML belongs on short TTLs, static assets on versioned filenames.

Misconfiguration three: allowing only CloudFront IP ranges in the origin security group while forgetting custom origins. CloudFront IP ranges change, so hardcoding them eventually breaks, and custom origins often miss the origin port, which shows up as intermittent 504s.

On positioning: CloudFront's strength is not having the most nodes (600+ points of presence is top tier but not unique) but its deep binding to the AWS ecosystem: S3 egress through the CDN gets a dedicated discount, OAC keeps the origin invisible, and signed URLs and cookies fit paid content naturally. The weakness is equally clear: configuration is spread across cache policies, origin groups, functions, and logging services, so the learning curve is steep, and there are no mainland China nodes, meaning China-facing businesses need a domestic CDN alongside it. For global edge network trade-offs, see our CDN provider selection guide.

7.2 Configuration checklist

  • Origins: S3 behind OAC rather than public read; custom origins with verified port, protocol, and Host header
  • Origin groups: both primary and secondary tested for failover, with failback conditions defined
  • Cache key: only content-changing dimensions, with query parameters allowlisted instead of fully forwarded
  • TTL: 30 days or more for static assets, short TTL for HTML, minimum TTL not zero
  • Origin headers: confirm the priority between origin Cache-Control and distribution TTLs behaves as intended
  • Certificates: ACM certificate in us-east-1, alternate domain added, distribution status Enabled
  • Update strategy: versioned static assets, targeted invalidation for HTML, full-site /* used sparingly
  • Observability: dashboards for hit ratio, 5xx, and time to first byte, with logs delivered to S3
  • Cost: Price Class narrowed to actual user distribution, with budget alarms on egress
  • Mainland access: add a domestic CDN when China nodes are required, following the cross-border pattern in Alibaba Cloud ECS vs Tencent Cloud CVM

One caveat: CloudFront's value shifts a lot with whether the origin lives inside AWS. With an S3 or ALB origin, its integration benefits arrive almost for free; with an origin on another cloud or in a self-built data center, the return shrinks to "a feature-complete but configuration-heavy CDN". If the origin sits on an overseas VPS, compare node distribution in the Vultr vs Linode vs DigitalOcean comparison before choosing the edge layer.

Official documentation: CloudFront Developer Guide https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/; creating a distribution https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-creating-console.html; invalidation and quotas https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html.

Source: AWS official documentation, compiled and interpreted by 16IDC — configuration names and quotas follow the CloudFront Developer Guide; quotas, prices, and features change by region and release, so verify against the official docs before making changes.

Integration & Code Examples

Example 1: Create an invalidation and confirm distribution status

# List distributions to get the DistributionId and current status
aws cloudfront list-distributions \
  --query 'DistributionList.Items[].{Id:Id,Domain:DomainName,Status:Status}' \
  --output table

# Invalidate only changed paths instead of a costly /* invalidation
aws cloudfront create-invalidation \
  --distribution-id "$CF_DISTRIBUTION_ID" \
  --paths "/index.html" "/static/app.css" "/blog/*"

# Check whether the invalidation finished
aws cloudfront list-invalidations --distribution-id "$CF_DISTRIBUTION_ID" \
  --query 'InvalidationList.Items[0].{Status:Status,Paths:InvalidationBatch.Paths}'

Path-level invalidation balances cost and freshness; full invalidation is for whole-site releases.

Example 2: Inspect cache behavior and managed cache policy TTLs

# Which cache policy is the default behavior using?
aws cloudfront get-distribution-config --id "$CF_DISTRIBUTION_ID" \
  --query 'DistributionConfig.DefaultCacheBehavior.{Policy:CachePolicyId,MinTTL:MinTTL,MaxTTL:MaxTTL,Compress:Compress}'

# List managed cache policies and their TTL floors
aws cloudfront list-cache-policies --type managed \
  --query 'CachePolicyList.Items[].CachePolicy.CachePolicyConfig.{Name:Name,MinTTL:MinTTL,DefaultTTL:DefaultTTL}' \
  --output table

# Confirm the origin uses OAC rather than the retired OAI
aws cloudfront get-distribution-config --id "$CF_DISTRIBUTION_ID" \
  --query 'DistributionConfig.Origins.Items[].{Id:Id,S3OriginConfig:S3OriginConfig,OriginAccessControlId:OriginAccessControlId}'

Once TTLs and the cache key are settled, hit ratio and origin load are largely decided.

Limitations

  • Someone who learns the bucket domain still cannot pull content around the CDN.
  • Names and tags do not change distribution behavior, but adding tags after the bill arrives leaves past usage impossible to attribute.
  • The origin host header must be set explicitly, otherwise virtual hosts on the origin fail to match and surface as 403 or 404 responses.
  • Two things must be decided alongside the group: the status-code range that triggers failover, and the failback policy after switching.
  • That single choice decides hit ratio, and it decides how many origin fetches the origin must absorb.

FAQ

Should I pick an S3 origin or a custom one?

Pick S3 with OAC for static assets. Use a custom origin when the site runs on EC2, an ALB or another cloud. On the S3 path the priority is locking the bucket to CloudFront access instead of public read. A custom origin needs the back-to-origin Host header set explicitly, or virtual hosts fail to match and return 403 or 404.

How are invalidations billed past the free tier?

The free allowance is 1,000 paths a month. Beyond that each path costs roughly $0.005. A /* wildcard counts as 1 path but clears every edge location, and doing it often drops the hit ratio during peak traffic. Versioned filenames consume no quota, which makes them the safer default.

What prerequisites does a custom domain need?

Three: an ACM certificate, an alternate domain name and a DNS record. The certificate must live in us-east-1 or the distribution cannot select it; point DNS at the *.cloudfront.net hostname, using an alias record on Route 53 since an apex domain cannot be a CNAME. Confirm the status reads Enabled before switching DNS.

When is CloudFront not a fit?

Two cases. If most users sit in mainland China, CloudFront has no mainland nodes and you need a domestic CDN alongside. If the origin lives outside AWS and signed URLs are not needed, the gain shrinks to a feature-rich but config-heavy CDN. With an S3 or ALB origin, integration arrives at almost no extra work.

Related Providers

  • AWS CloudFront: when origins are S3 or ALB and signed URLs plus edge functions enforce access.
  • Cloudflare: when the same static assets must be cached across clouds without an AWS account.

Community & Resources

Learning resources and tools

Original source: AWS Documentation ↗