Hosting a static site on S3 and CloudFront

Beginner · 11 min

A private bucket behind CloudFront with origin access control, a custom domain, caching headers, error pages and a deploy that rolls back.

Before thisS3 access control and Block Public AccessRoute 53 records and routing policiesTLS certificates with ACMCloudFront and edge caching

ProgramGuru · 11 min

Hosting a static site on S3 and CloudFront

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by ProgramGuruReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Keep the bucket private with Block Public Access on, and let only your distribution read it through origin access control.
  • Use the bucket's REST endpoint as the origin. The S3 website endpoint can't use origin access control.
  • The default root object covers only the root URL. Subdirectory index pages need a CloudFront Function.
  • A missing object usually comes back as 403 from a private bucket, so map it to your 404 page.
  • The certificate goes in us-east-1, and Route 53 alias records point the domain at the distribution.
  • Cache hashed assets for a year and HTML not at all, upload assets before HTML, and keep old assets around.

Files don’t need servers

A built front end is just files. Running a web server to hand out files means patching and scaling something that does almost nothing. Put the files in S3 and let CloudFront serve them. You get HTTPS, global caching and no machines.

Old tutorials make the bucket public and turn on S3 static website hosting. That endpoint is HTTP only and requires opening the bucket. Don’t. Keep the bucket private and let one distribution read it.

Origin access control

With origin access control (OAC), CloudFront signs each request to S3, and the bucket policy admits CloudFront’s service principal for your distribution only. Here is the whole core as a CloudFormation template:

Resources:
  SiteBucket:
    Type: AWS::S3::Bucket

  OAC:
    Type: AWS::CloudFront::OriginAccessControl
    Properties:
      OriginAccessControlConfig:
        Name: !Sub ${AWS::StackName}-oac
        OriginAccessControlOriginType: s3
        SigningBehavior: always
        SigningProtocol: sigv4

  Distribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Enabled: true
        HttpVersion: http2and3
        DefaultRootObject: index.html
        Origins:
          - Id: site
            DomainName: !GetAtt SiteBucket.RegionalDomainName
            OriginAccessControlId: !GetAtt OAC.Id
            S3OriginConfig: {OriginAccessIdentity: ""}
        DefaultCacheBehavior:
          TargetOriginId: site
          ViewerProtocolPolicy: redirect-to-https
          Compress: true
          CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6  # CachingOptimized
        CustomErrorResponses:
          - {ErrorCode: 403, ResponseCode: 404, ResponsePagePath: /404.html}

  SiteBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref SiteBucket
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: {Service: cloudfront.amazonaws.com}
            Action: s3:GetObject
            Resource: !Sub ${SiteBucket.Arn}/*
            Condition:
              StringEquals:
                AWS:SourceArn: !Sub arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${Distribution}

Outputs:
  Url:
    Value: !Sub https://${Distribution.DomainName}
  BucketName:
    Value: !Ref SiteBucket

The origin is the regional REST domain name. The empty OriginAccessIdentity tells CloudFront this is an S3 origin that doesn’t use the older OAI mechanism. If the bucket uses SSE-KMS, the key policy must also let CloudFront decrypt. Stacks get their own lesson.

What each piece is doing

Read the template as a chain of trust. The bucket holds files and admits nobody new by default. The access control object tells CloudFront to sign every origin request with SigV4. The distribution is the only public part: it terminates TLS, redirects plain HTTP, compresses text and caches. The bucket policy closes the loop by naming one service and one distribution.

None of these lets a visitor list or read the bucket directly. Check that after deploying: the CloudFront URL should return your page, and the S3 object URL should return AccessDenied. If the S3 URL works, something has made the bucket public.

There’s no logging, firewall or security header in this minimal version. For a real site, add a response headers policy for HSTS and related headers, turn on access logs, and consider AWS WAF. Enable versioning on the bucket if you want to recover overwritten files.

Two surprises

DefaultRootObject serves index.html for / only. A request for /docs/ does not find docs/index.html. Fix it with a CloudFront Function on viewer request that appends index.html to paths ending in a slash.

And a missing file comes back as 403, not 404, because the policy grants reading objects but not listing them, so S3 won’t reveal whether a key exists. The custom error response above maps it to your 404 page. A single-page app instead returns /index.html with status 200, but beware: that also hides real permission errors.

Your own domain

  1. Request a certificate in us-east-1 with ACM.
  2. Add the domain to the distribution’s alternate names and attach the certificate.
  3. Create Route 53 A and AAAA alias records pointing at the distribution.

Deploying

Give the two kinds of file different cache headers:

aws s3 sync dist/assets s3://$BUCKET/assets \
  --cache-control 'public,max-age=31536000,immutable'
aws s3 sync dist s3://$BUCKET --exclude 'assets/*' \
  --cache-control 'no-cache'

Hashed assets can be cached for ever since their names change. HTML must be revalidated so users find the new names. Order matters: assets first, HTML second. Don’t use --delete on the assets in the same step, or users holding the old HTML will request files you just removed. Expire old builds later.

Rollback is republishing the previous HTML. Run the deploy from CI using a short-lived role, with permission to write that bucket and nothing more.

When something is wrong

  • AccessDenied on every path: the bucket policy is missing, names the wrong distribution ARN, or the origin isn’t using the access control.
  • AccessDenied only on /: no default root object.
  • Old content after a deploy: HTML was uploaded without no-cache, so edges and browsers are holding it. Fix the header, then invalidate once.
  • Certificate can’t be selected: it isn’t in us-east-1 or isn’t issued yet.
  • Domain doesn’t load: the name isn’t listed on the distribution, or the alias record is missing.

Check response headers before guessing. x-cache tells you whether CloudFront served a hit or went to the origin, and cache-control shows what you actually uploaded. Keep the whole setup in a template so a second environment is one command, and delete test stacks after emptying their buckets, because CloudFormation won’t remove a bucket that still has objects.

For cost, a small site typically fits inside CloudFront’s free allowances, with S3 storage the main line item. A budget alert tells you if traffic says otherwise.

About the video

The embed is ProgramGuru’s 11-minute walkthrough from August 2026. Its description builds a private bucket behind CloudFront on the free plan, connects a Route 53 domain with HTTPS, and fixes AccessDenied with the default root object. It uses the console, not a template. There are no chapters or audio-language flag; I judged it from the description, which is in English.

What was run: the template passes cfn-lint 1.41.0. moto couldn’t create it, failing on the CloudFront resources, so it has not been deployed anywhere. Both sync commands ran against a moto bucket and the cache headers showed up on the objects. OAC, root object and error behaviour come from the CloudFront developer guide, checked in November 2026.

Check yourself

  1. 01The home page works but /docs/ returns AccessDenied, although docs/index.html exists. Why?

    The default root object applies only to the root URL, and the REST origin has no concept of directory indexes. A CloudFront Function can append index.html to paths ending in a slash.

  2. 02Why does the bucket policy name the distribution's ARN in a condition?

    The principal is the CloudFront service, which every AWS customer can use. AWS:SourceArn restricts the grant to your distribution, so someone else's can't read your bucket.

  3. 03During a deploy a user loads new HTML that references a script not yet uploaded. How do you prevent it?

    Upload the new hashed assets first and the HTML last, and don't delete the previous build's assets straight away.

  4. 04You enable S3 static website hosting and then try to attach origin access control. Why does it fail to work?

    The website endpoint is a plain HTTP custom origin that can't verify signed requests. Use the bucket's REST endpoint as an S3 origin.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark