Cloud & Hosting (AWS)

AWS CloudFront Setup & Deployment Guide

Global CDN for fast, secure delivery – serve a React/static site from a private S3 bucket with HTTPS, a custom domain and cache invalidation.

Updated Official documentation ↗

1. Introduction & use cases

Amazon CloudFront is AWS’s content delivery network (CDN). It caches your files at hundreds of edge locations worldwide (including several in India), so users download from a nearby location – faster pages and less load on your origin.

The classic setup is a static site or SPA in a private S3 bucket with CloudFront in front using Origin Access Control (OAC), an ACM certificate for HTTPS on your own domain, and invalidations after each deploy. CloudFront can also sit in front of EC2, load balancers or APIs to add HTTPS, caching and DDoS protection.

Where it is used

  • Hosting React, Vue, Angular or static sites
  • Serving images, videos and downloads fast worldwide
  • HTTPS and caching in front of APIs/servers
  • Protecting origins with AWS WAF and Shield

2. Prerequisites

You needVersion / notes
AWS accountWith MFA on the root user and a non-root admin identity
AWS CLI v2Installed and configured – see the AWS guide
S3 bucket with your siteSee the S3 guide
DomainRoute 53 or any DNS provider

3. Local setup

  1. 1Build the site

    Any static output works; for a React (Vite) app:

    BASH
    npm ci
    npm run build     # creates dist/
  2. 2Create a private bucket and upload

    Keep Block Public Access on – CloudFront will read the bucket privately.

    BASH
    aws s3 mb s3://example-com-site --region ap-south-1
    aws s3 sync dist/ s3://example-com-site/ --delete

4. Create & run a project

  1. 1Request an ACM certificate in us-east-1

    CloudFront only uses certificates from N. Virginia (us-east-1). Use DNS validation and add the CNAME records it shows (one click if you use Route 53).

    BASH
    aws acm request-certificate --region us-east-1 \
      --domain-name example.com --subject-alternative-names www.example.com \
      --validation-method DNS
  2. 2Create the distribution

    CloudFront console → Create distribution: origin = your S3 bucket → Origin access: Origin access control (create new OAC) → Viewer protocol policy Redirect HTTP to HTTPS → Cache policy CachingOptimized → Alternate domain names example.com, www.example.com → choose the ACM certificate → Default root object index.html.

  3. 3Allow CloudFront to read the bucket

    The console shows a bucket policy for the OAC – copy it to the bucket’s Permissions → Bucket policy. It looks like this:

    bucket-policy.json
    {
      "Version": "2012-10-17",
      "Statement": [{
        "Sid": "AllowCloudFrontServicePrincipal",
        "Effect": "Allow",
        "Principal": { "Service": "cloudfront.amazonaws.com" },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::example-com-site/*",
        "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE" } }
      }]
    }
  4. 4Make SPA routes work

    With a private S3 origin, unknown paths return 403. Add Error pages: 403 and 404 → response page /index.html, HTTP code 200, so React Router routes load after refresh.

  5. 5Test the CloudFront URL

    Open https://dxxxxxxxxxxxx.cloudfront.net – the site should load over HTTPS.

    BASH
    curl -I https://dxxxxxxxxxxxx.cloudfront.net
    # HTTP/2 200 … x-cache: Miss from cloudfront (Hit on the next request)

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

A static site has no server-side secrets. Build-time variables (e.g. VITE_API_URL) are baked into the files – set them before npm run build for each environment.

.env
# deployment script variables
S3_BUCKET=example-com-site
CF_DISTRIBUTION_ID=EDFDVBD6EXAMPLE
VITE_API_URL=https://api.example.com

Key dependencies

Package / toolUsed for
CloudFront distributionCDN with edge caching
Origin Access Control (OAC)Private S3 access for CloudFront
ACM (us-east-1)Free TLS certificates
Route 53 (optional)Alias records to the distribution
Cache policiesWhat is cached and for how long
AWS WAF (optional)Web application firewall

Folder structure

project structure
example-com-site (private bucket)
├── index.html          # short cache
├── assets/
│   ├── index-a1b2c3.js # hashed → cache for a year
│   └── index-d4e5f6.css
└── favicon.ico

Essential commands

CommandWhat it does
aws s3 sync dist/ s3://bucket/ --deleteUpload the new build
aws cloudfront create-invalidation --distribution-id ID --paths "/*"Clear cached files
aws cloudfront list-distributionsFind IDs and domains
curl -I URLCheck x-cache Hit/Miss

6. Production deployment

Server & hosting requirements

RequirementRecommendation
OriginPrivate S3 bucket with OAC (or EC2/ALB/API)
CertificateACM in us-east-1 covering all alternate domains
DNSAlias/CNAME from your domain to the distribution
CachingLong cache for hashed assets, short for index.html
SecurityRedirect HTTP→HTTPS, optional WAF, security headers policy

Deployment steps

  1. 1Point the domain

    Route 53: create an A (Alias) record for example.com and www → the CloudFront distribution. Other DNS providers: CNAME www → dxxxx.cloudfront.net; for the apex use their ALIAS/ANAME feature or redirect to www.

    OUTPUT
    # Route 53 alias
    # example.com      A  ALIAS  dxxxxxxxxxxxx.cloudfront.net
    # www.example.com  A  ALIAS  dxxxxxxxxxxxx.cloudfront.net
  2. 2Upload with the right cache headers

    Hashed assets can be cached for a year; index.html must be re-checked often.

    BASH
    aws s3 sync dist/ s3://example-com-site/ --delete \
      --exclude index.html --cache-control "public,max-age=31536000,immutable"
    aws s3 cp dist/index.html s3://example-com-site/index.html \
      --cache-control "no-cache"
  3. 3Invalidate after each deploy

    Clears edge caches so users get the new index.html immediately.

    BASH
    aws cloudfront create-invalidation --distribution-id EDFDVBD6EXAMPLE --paths "/index.html" "/"
  4. 4Automate it

    Run build → sync → invalidate in CI (e.g. GitHub Actions with an OIDC role allowed s3:*Object, s3:ListBucket on the bucket and cloudfront:CreateInvalidation).

  5. 5CloudFront in front of a server/API (optional)

    Add an origin pointing to your EC2/ALB domain, use cache policy CachingDisabled and origin request policy AllViewer for dynamic paths like /api/*, and keep CachingOptimized for static paths.

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ curl -I https://example.comHTTP/2 200content-type: text/htmlserver: AmazonS3x-cache: Hit from cloudfrontvia: 1.1 3c6c...cloudfront.net (CloudFront)x-amz-cf-pop: BOM78-P1age: 112
Figure 1: terminal output of the sample AWS CloudFront project (section 4).
1npm run build2s3 sync (privatebucket)3CloudFront + OAC4ACM cert + DNSalias5Invalidate → users
Figure 2: production deployment flow (section 6).
example-com-site (private bucket)├── index.html # short cache├── assets/│ ├── index-a1b2c3.js # hashed → cache for a year│ └── index-d4e5f6.css└── favicon.ico
Figure 3: project folder structure (section 5).

8. Common errors & solutions

403 AccessDenied from CloudFront

The bucket policy does not allow this distribution (OAC), the object key is wrong, or there is no default root object index.html.

Refreshing /about gives 403/404

Add custom error responses 403 and 404 → /index.html with HTTP 200 for SPAs.

Certificate not listed when editing the distribution

It must be in us-east-1 and cover the exact alternate domain names (and be validated).

CNAMEAlreadyExists

Another distribution (maybe in another account) already uses that domain. Remove it there first.

Users still see the old site

Cached index.html. Invalidate /index.html (or /*) and set Cache-Control: no-cache for it.

Best practices

  • Keep the bucket private with OAC – never a public website bucket.
  • Hashed file names + long caching; no-cache for HTML.
  • Redirect HTTP to HTTPS; add a response headers policy (HSTS etc.).
  • Invalidate only what changed; automate deploys in CI.
  • Use AWS WAF for login/API paths that face abuse.