Home AWSHost a Static Website on Amazon S3 with CloudFront

Host a Static Website on Amazon S3 with CloudFront

by Knowledge Base Linux
Host a Static Website on Amazon — Host a Static Website on Amazon S3 with CloudFront

Hosting an s3 static website behind a CloudFront CDN is one of the cheapest, most scalable ways to publish a site on AWS: no servers to patch, no operating system to harden, and global edge caching that makes pages load fast everywhere. In this guide you will create an S3 bucket, upload a static site with the AWS CLI, front it with a CloudFront distribution using Origin Access Control (OAC), add HTTPS, and learn how to invalidate the cache when you deploy updates. This article covers Host a Static Website on Amazon in detail.

S3 static website deployment flow illustration: syncing files to a bucket and refreshing edge caches worldwide

This s3 static website setup follows current AWS best practice — a private bucket with OAC rather than a wide-open public bucket — so your origin stays locked down while visitors get fast, encrypted delivery through CloudFront.

Prerequisites – Host a Static Website on Amazon

  • An AWS account with permissions for S3, CloudFront, and (optionally) ACM and Route 53.
  • AWS CLI v2 installed and configured (aws configure), or equivalent credentials in your environment.
  • A simple static site: at minimum an index.html file and optionally an error.html page, CSS, and images.
  • (Optional) A custom domain managed in Route 53 and an ACM certificate, if you want https://www.example.com instead of the CloudFront domain.

Step 1: Create the S3 Bucket with a Proper Name – Host a Static Website on Amazon

Bucket names are globally unique across all of AWS, so pick something distinctive. For an s3 static website you will front with CloudFront, the bucket name does not need to match your domain, but it must be DNS-compliant: lowercase letters, numbers, and hyphens only. Avoid dots in the name — they break HTTPS certificate validation on virtual-hosted-style URLs.

# Choose your region (us-east-1 shown here)
export AWS_REGION=us-east-1
export BUCKET=my-static-site-2026-unique

# Create the bucket (us-east-1 needs no LocationConstraint)
aws s3api create-bucket --bucket $BUCKET

# Keep Block Public Access ON — CloudFront OAC will access the bucket privately
aws s3api put-public-access-block --bucket $BUCKET \
  --public-access-block-configuration \
  BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true

If you create the bucket in any region other than us-east-1, add --create-bucket-configuration LocationConstraint=$AWS_REGION to the create-bucket call.

Step 2: Enable Static Website Hosting on the Bucket

Even though CloudFront will be the public entry point, enabling website hosting on the bucket configures the index and error documents. (With OAC we will point CloudFront at the bucket’s REST endpoint, not the website endpoint — more on why in a moment.)

aws s3api put-bucket-website --bucket $BUCKET \
  --website-configuration '{
    "IndexDocument": {"Suffix": "index.html"},
    "ErrorDocument": {"Key": "error.html"}
  }'

Verify it:

aws s3api get-bucket-website --bucket $BUCKET

Step 3: Upload Your Site with the AWS CLI

Use aws s3 sync to upload a local site folder. The command below uploads everything, sets sensible cache headers for HTML versus long-lived assets, and deletes remote files you removed locally:

cd ~/my-site

# Upload the whole site
aws s3 sync . s3://$BUCKET --delete \
  --exclude "*.map"

# Short cache for HTML so edits go live quickly...
aws s3 cp s3://$BUCKET s3://$BUCKET --recursive \
  --exclude "*" --include "*.html" \
  --metadata-directive REPLACE \
  --cache-control "max-age=300" \
  --content-type "text/html"

# ...and long cache for versioned assets
aws s3 cp s3://$BUCKET s3://$BUCKET --recursive \
  --exclude "*" --include "assets/*" \
  --metadata-directive REPLACE \
  --cache-control "max-age=31536000,immutable"

Confirm the upload:

aws s3 ls s3://$BUCKET --recursive | head

Step 4: Create the CloudFront Distribution with OAC

Origin Access Control (OAC) is the modern replacement for the legacy Origin Access Identity. It lets CloudFront read from your private bucket using short-term SigV4-signed requests, so no bucket policy opening the bucket to the world is needed. This is the recommended architecture for every s3 static website today.

Create the OAC first:

OAC_ID=$(aws cloudfront create-origin-access-control \
  --origin-access-control-config '{
    "Name": "s3-static-site-oac",
    "Description": "OAC for static website bucket",
    "SigningProtocol": "sigv4",
    "SigningBehavior": "always",
    "OriginAccessControlOriginType": "s3"
  }' --query 'OriginAccessControl.Id' --output text)

echo "OAC ID: $OAC_ID"

Now create the distribution. Save this as dist-config.json, replacing BUCKET and OAC_ID with your values:

{
  "CallerReference": "static-site-2026-10-23",
  "Comment": "S3 static website via CloudFront OAC",
  "Enabled": true,
  "DefaultRootObject": "index.html",
  "Origins": {
    "Quantity": 1,
    "Items": [
      {
        "Id": "s3-origin",
        "DomainName": "BUCKET.s3.us-east-1.amazonaws.com",
        "S3OriginConfig": { "OriginAccessIdentity": "" },
        "OriginAccessControlId": "OAC_ID"
      }
    ]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "s3-origin",
    "ViewerProtocolPolicy": "redirect-to-https",
    "AllowedMethods": {
      "Quantity": 2,
      "Items": ["GET", "HEAD"],
      "CachedMethods": { "Quantity": 2, "Items": ["GET", "HEAD"] }
    },
    "Compress": true,
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "OriginRequestPolicyId": "88a5eaf4-2fd4-4709-b370-b4c650ea3fcf"
  },
  "PriceClass": "PriceClass_100"
}

A few notes on the values above: DefaultRootObject: index.html serves your homepage at /. redirect-to-https forces encrypted delivery. Compress: true enables gzip/Brotli. The two policy IDs are AWS-managed policies (CachingOptimized and CORS-S3Origin). PriceClass_100 uses only the cheapest edge locations (US, Canada, Europe) — switch to PriceClass_All for global coverage.

# Substitute your values and create the distribution
sed -i "s/BUCKET/$BUCKET/g; s/OAC_ID/$OAC_ID/g" dist-config.json

DIST_ID=$(aws cloudfront create-distribution \
  --distribution-config file://dist-config.json \
  --query 'Distribution.Id' --output text)

aws cloudfront wait distribution-deployed --id $DIST_ID

DOMAIN=$(aws cloudfront get-distribution --id $DIST_ID \
  --query 'Distribution.DomainName' --output text)
echo "Your site: https://$DOMAIN"

Deployment takes roughly 5–15 minutes. The wait command blocks until the status is Deployed.

Step 5: Grant CloudFront Access with a Bucket Policy

With OAC, the bucket stays private and only your distribution may read it. Attach a policy that allows s3:GetObject solely when the request comes through your distribution’s ARN:

ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

aws s3api put-bucket-policy --bucket $BUCKET --policy "{
  \"Version\": \"2012-10-17\",
  \"Statement\": [
    {
      \"Sid\": \"AllowCloudFrontOAC\",
      \"Effect\": \"Allow\",
      \"Principal\": { \"Service\": \"cloudfront.amazonaws.com\" },
      \"Action\": \"s3:GetObject\",
      \"Resource\": \"arn:aws:s3:::$BUCKET/*\",
      \"Condition\": {
        \"StringEquals\": {
          \"AWS:SourceArn\": \"arn:aws:cloudfront::$ACCOUNT_ID:distribution/$DIST_ID\"
        }
      }
    }
  ]
}"

The AWS:SourceArn condition is the key security control: even though the principal is the CloudFront service, only your distribution can fetch objects. Direct access to the bucket’s REST endpoint from a browser is denied.

Step 6: Add a Custom Domain and HTTPS (Optional)

To serve your s3 static website from www.example.com instead of the cloudfront.net hostname:

  1. Request an ACM certificate in us-east-1 (CloudFront only accepts certificates from that region):
    aws acm request-certificate --region us-east-1 \
      --domain-name www.example.com \
      --validation-method DNS

    Approve it by creating the DNS validation CNAME records ACM shows you.

  2. Attach the certificate and domain to the distribution with aws cloudfront update-distribution, setting Aliases to ["www.example.com"] and ViewerCertificate to the ACM certificate ARN with SSLSupportMethod: sni-only.
  3. Point DNS at CloudFront: in Route 53, create an Alias A record for www.example.com targeting the CloudFront distribution. Alias records are free and required — a plain CNAME also works but cannot sit at the zone apex.

For EC2-based workloads where you need shell access without opening any inbound ports, the same AWS account can use Session Manager for port-free EC2 access — a handy companion technique for hybrid static-plus-dynamic architectures.

Step 7: Invalidate the Cache on Deploy

CloudFront caches your files at the edge, so uploading a new index.html to S3 alone will not update what visitors see until the TTL expires. Invalidate the changed paths after each deploy:

# Invalidate the homepage and everything under /assets/
aws cloudfront create-invalidation --distribution-id $DIST_ID \
  --paths "/index.html" "/assets/*"

A typical deploy script for an s3 static website therefore looks like: aws s3 sync, then create-invalidation for the changed paths. AWS gives you 1,000 free invalidation paths per month; beyond that they are billed per path, so prefer invalidating specific files over /* (which also evicts your long-cached assets unnecessarily).

To make deployments fully hands-off, wire these two commands into your CI pipeline — the same GitHub Actions or Jenkins flow you use for application code can publish the static site on every merge to main.

Troubleshooting a CloudFront + S3 Static Website

403 “Access Denied” from CloudFront

The most common cause is a bucket policy that does not match the distribution ARN, or OAC attached to the wrong origin. Re-check that the AWS:SourceArn condition contains your exact distribution ID and that the OAC ID in the distribution config is correct. Also confirm Block Public Access is not conflicting with an older public-read policy.

403 on sub-paths but the homepage works

S3’s REST endpoint (which OAC uses) does not apply the website endpoint’s index-document behavior to subdirectories: /docs/ will not automatically serve /docs/index.html. Either use CloudFront Functions to rewrite directory URLs, or link to full object keys.

Site shows an old version after deploying

You forgot the invalidation step, or the browser cached the page. Create an invalidation for the changed paths and hard-refresh. For HTML files, the short max-age=300 cache-control set in Step 3 limits this pain.

“The request could not be satisfied” / 503 errors

Usually a transient issue while the distribution is still deploying. Wait for aws cloudfront wait distribution-deployed to finish before testing. Persistent 503s point at an origin problem — verify the bucket name in the origin domain.

Certificate errors on a custom domain

The ACM certificate must live in us-east-1, must cover the exact domain in Aliases, and must be validated (status ISSUED). A certificate in any other region will not appear in the CloudFront console at all.

S3 Static Website Cost Notes

An s3 static website is one of the cheapest things you can run on AWS. S3 Standard storage is roughly $0.023/GB-month, PUT/GET requests cost fractions of a cent per thousand, and CloudFront’s free tier includes 1 TB of data transfer out plus 10 million requests per month for the first year. A small marketing site typically lands well under $1/month — and often inside the free tier entirely. Watch out for two cost traps: excessive /* invalidations beyond the 1,000 free paths/month, and PriceClass_All if your audience is regional — PriceClass_100 keeps edge costs down for US/EU visitors.

Conclusion

You now have a production-grade s3 static website: a private S3 bucket holding your files, a CloudFront distribution delivering them globally over HTTPS via Origin Access Control, a locked-down bucket policy, and a deploy workflow with targeted cache invalidations. From here you can layer on a custom domain with ACM and Route 53, add a CloudFront Function for clean URLs, or automate the whole pipeline in CI. For the official reference on every website-hosting setting, see the AWS S3 website hosting documentation.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.