AboutProjectsWorkBlogContact
Home / Blog / AWS, Deployment & DevOps

Configuring AWS CloudFront With S3 for Static Website Delivery

Keep the bucket private, serve through CloudFront, add HTTPS and a custom domain, and invalidate cleanly.

By Hamza JanzaibNovember 28, 202617 min readIntermediate
Paste it into ChatGPT, Claude or any AI assistant.
  • aws
  • cloudfront
  • s3
  • https
  • cdn
On this page ยท 14 sections
  • The target architecture
  • Why use CloudFront here
  • Step 1: Request a certificate (us-east-1)
  • Step 2: Create the distribution
  • Step 3: Allow only CloudFront to read the bucket
  • Step 4: Fix single-page-app routing
  • Step 5: Point your domain at CloudFront
  • Step 6: Deploy and invalidate
  • Security considerations
  • Performance considerations
  • Troubleshooting
  • Testing and validation
  • Best practices
  • Conclusion

Serving a website straight from an S3 website endpoint works, but it has limits: no HTTPS, no custom domain with TLS, a public bucket and no edge caching. Amazon CloudFront fixes all four. This guide puts CloudFront in front of a private S3 bucket using Origin Access Control, adds HTTPS on your own domain, handles single-page-app routing and sets up a clean deployment and invalidation workflow.

It assumes you already have a static site in an S3 bucket. If not, start with the guide on hosting a static website on AWS S3.

The target architecture

  1. 1Browser

    HTTPS request

  2. 2CloudFront

    edge cache, TLS, custom domain

  3. 3S3 bucket (private)

    read through a signed OAC request

The bucket is private; only your distribution can read it

The bucket stays private. Only the CloudFront distribution is allowed to read it, which removes a whole category of mistakes caused by public buckets.

Why use CloudFront here

  • HTTPS everywhere with a free certificate from AWS Certificate Manager.
  • Lower latency because content is cached at edge locations near users.
  • A private bucket, so objects cannot be fetched directly from S3.
  • Compression (gzip and Brotli) handled for you.
  • Control over caching and headers per path.

Step 1: Request a certificate (us-east-1)

CloudFront reads TLS certificates from US East (N. Virginia), regardless of where your bucket lives. Switch the console region to us-east-1, open AWS Certificate Manager, and request a public certificate for your domain (and www if you use it):

bash
aws acm request-certificate \  --region us-east-1 \  --domain-name example.com \  --subject-alternative-names www.example.com \  --validation-method DNS

Add the CNAME records ACM shows you to your DNS zone. With Route 53 the console can create them in one click. Wait until the status is Issued before creating the distribution.

Step 2: Create the distribution

In the CloudFront console choose Create distribution and set:

  1. Origin domain: pick the bucket's S3 REST endpoint (my-bucket.s3.us-east-1.amazonaws.com), not the website endpoint.
  2. Origin access: Origin access control settings (recommended) โ†’ create a new OAC (signing behavior: Sign requests).
  3. Viewer protocol policy: Redirect HTTP to HTTPS.
  4. Default root object: index.html.
  5. Compress objects automatically: on.
  6. Alternate domain names (CNAMEs): example.com, www.example.com.
  7. Custom SSL certificate: choose the ACM certificate from Step 1.

For the cache policy, the managed CachingOptimized policy is a good default for static assets.

When you create the distribution, the console shows a ready-made bucket policy for the OAC. Copy it.

Step 3: Allow only CloudFront to read the bucket

Replace any public-read policy with one that trusts CloudFront and is scoped to your distribution:

json
{  "Version": "2012-10-17",  "Statement": [    {      "Sid": "AllowCloudFrontServicePrincipalReadOnly",      "Effect": "Allow",      "Principal": { "Service": "cloudfront.amazonaws.com" },      "Action": "s3:GetObject",      "Resource": "arn:aws:s3:::my-bucket/*",      "Condition": {        "StringEquals": {          "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E1ABCDEXAMPLE"        }      }    }  ]}

The AWS:SourceArn condition is what ties access to this one distribution. Without it, any CloudFront distribution in any account could request your objects through the service principal.

Now turn Block Public Access back on for the bucket. The site keeps working because CloudFront reads it through the policy above, while direct S3 URLs return an access error.

Step 4: Fix single-page-app routing

If your site is a single-page app, a request for /dashboard looks for an object that does not exist. With a private bucket and OAC, S3 answers 403 Forbidden (CloudFront has no ListBucket permission, so S3 hides whether the object exists). Map the errors to your app shell under Error pages โ†’ Create custom error response:

HTTP error codeResponse page pathHTTP response code
403/index.html200
404/index.html200

Set an error caching minimum TTL of around 10 seconds so a bad deploy does not stay cached for long.

If your site is a static export where every route has its own HTML file (about/index.html), CloudFront's default root object only applies to the site root, not to subfolders. A small CloudFront Function can rewrite /about/ to /about/index.html:

js
// CloudFront Function: viewer requestfunction handler(event) {  var request = event.request;  var uri = request.uri;  if (uri.endsWith("/")) {    request.uri += "index.html";  } else if (!uri.includes(".")) {    request.uri += "/index.html";  }  return request;}

Step 5: Point your domain at CloudFront

In Route 53, create alias records (type A, and AAAA if IPv6 is enabled) for example.com and www.example.com targeting the distribution. Alias records work at the zone apex, which a normal CNAME cannot. If your DNS is elsewhere, create a CNAME for www to the dxxxxxxxx.cloudfront.net domain and use your provider's ALIAS/ANAME feature for the apex.

bash
dig +short example.comcurl -I https://example.com

Look for HTTP/2 200, a via: ... (CloudFront) header and x-cache: Hit from cloudfront on repeat requests.

Step 6: Deploy and invalidate

A good deploy has two parts: upload with the right cache headers, then invalidate only what could be stale.

bash
#!/usr/bin/env bashset -euo pipefailBUCKET=my-bucketDISTRIBUTION_ID=E1ABCDEXAMPLEnpm run build# Fingerprinted files: cache for a yearaws s3 sync dist "s3://$BUCKET" --delete \  --exclude "index.html" \  --cache-control "public,max-age=31536000,immutable"# Entry point: always revalidateaws s3 cp dist/index.html "s3://$BUCKET/index.html" \  --cache-control "no-cache" --content-type "text/html"# Only the files that keep the same name need invalidatingaws cloudfront create-invalidation \  --distribution-id "$DISTRIBUTION_ID" \  --paths "/index.html"

Because bundlers produce new filenames for changed assets, you do not need /* on every deploy. Invalidate /index.html (and any other unhashed files, like a sitemap or robots.txt). AWS includes a number of free invalidation paths each month, but wildcard invalidations still add up and are slower than they need to be.

Security considerations

  • Keep the bucket private and the OAC policy scoped with AWS:SourceArn.
  • Use a security headers policy (managed or custom response headers policy) to add Strict-Transport-Security, X-Content-Type-Options and a Content Security Policy.
  • Keep the TLS security policy current (the default TLSv1.2_2021 or newer).
  • Deploy from CI using a role with only the S3 and invalidation permissions it needs.
  • Consider AWS WAF if the site accepts any user input or you need rate limiting.

Performance considerations

  • Enable HTTP/2 and HTTP/3 on the distribution.
  • Leave automatic compression on, and make sure files are cacheable so compression is applied once at the edge.
  • Use long TTLs for hashed assets and short or no-cache for HTML.
  • Pick the price class that matches your audience instead of all edge locations if cost matters.

Troubleshooting

SymptomLikely causeFix
AccessDenied XML from CloudFrontBucket policy missing or wrong distribution ARNRe-check the OAC bucket policy
403 on page refreshSPA routes with no custom error responseAdd the 403/404 โ†’ /index.html mapping
Old site after deployCached index.htmlInvalidate /index.html, check Cache-Control
Certificate not in dropdownACM certificate not in us-east-1Request it again in us-east-1
ERR_SSL_VERSION_OR_CIPHER_MISMATCHDomain not listed in the distribution's alternate namesAdd the CNAME and certificate
Domain does not resolveDNS record missing or still propagatingCheck the alias record with dig
/about/ returns the homepageSubfolder index not resolvedUse the CloudFront Function above

Testing and validation

bash
# Is the response served over HTTPS and from CloudFront?curl -sI https://example.com | grep -iE "HTTP/|x-cache|via|cache-control"# Is the bucket really private? (expect 403)curl -sI https://my-bucket.s3.us-east-1.amazonaws.com/index.html# A deep link should return your app, not an errorcurl -sI https://example.com/dashboard

Best practices

  • Prefer OAC over the legacy OAI and over public buckets.
  • Describe the whole setup in infrastructure as code (CDK or Terraform) so it is reproducible.
  • Keep separate distributions for staging and production.
  • Version your bucket if you want one-step rollbacks.
  • Track CloudFront metrics (error rate, cache hit ratio) in CloudWatch.

Conclusion

CloudFront turns an S3 bucket into a production static site: private storage, HTTPS on your domain, edge caching and clean deploys. The key details are easy to miss, a certificate in us-east-1, the S3 REST endpoint as the origin, a bucket policy scoped to your distribution, and error mappings for single-page-app routes. Get those right and the rest is a repeatable deploy script.

Frequently asked questions

+โˆ’Why use CloudFront instead of the S3 website endpoint?

The S3 website endpoint is HTTP only and serves from one region. CloudFront adds HTTPS, a custom domain, edge caching, compression and security headers, and lets the bucket stay completely private.

+โˆ’What is Origin Access Control (OAC)?

OAC lets CloudFront sign its requests to S3 so only your distribution can read the bucket. It replaces the older Origin Access Identity (OAI) and supports newer S3 features such as SSE-KMS encryption.

+โˆ’Why must my ACM certificate be in us-east-1?

CloudFront is a global service that reads certificates from the US East (N. Virginia) region. A certificate created in any other region will not appear in the CloudFront certificate list.

+โˆ’Why does my single-page app return 403 on refresh?

With a private bucket and OAC, a missing object returns 403 (not 404) because CloudFront has no ListBucket permission. Add custom error responses that map 403 and 404 to /index.html with a 200 status.

+โˆ’Do I have to invalidate the cache on every deploy?

Not for fingerprinted assets, because new builds produce new filenames. You only need to invalidate files that keep the same name, mainly index.html. Invalidating /index.html is cheaper and faster than invalidating everything.

+โˆ’Should I use the S3 REST endpoint or the website endpoint as the origin?

Use the S3 REST endpoint (bucket.s3.region.amazonaws.com) with OAC for a private bucket. The website endpoint requires a public bucket and cannot use OAC, so only choose it if you need S3 redirect rules or automatic index documents in subfolders.

+โˆ’How long does a new distribution take to deploy?

Typically a few minutes, but changes propagate to all edge locations asynchronously. Check the distribution status in the console and wait for Deployed before testing.

Further reading

  • docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html
  • docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

AWS, Deployment & DevOpsNovember 28, 202615 min readBeginner

Hosting a Static Website on AWS S3

Create a bucket, allow public reads, enable website hosting and deploy a build with one CLI command.

AWS, Deployment & DevOpsNovember 28, 202618 min readIntermediate

Deploying a Node.js Application on AWS EC2 From Scratch

The full path from an empty EC2 instance to a Node.js app behind Nginx and HTTPS, with troubleshooting.

Next.js, React & TypeScriptNovember 28, 202613 min readIntermediate

Managing API Caching and Data Fetching in Next.js

A mental model for Next.js caching layers and a repeatable pattern for fetching, caching and revalidating API data.

Built by Hamza Janzaib