Skip to main content

Cloud and deployment · Intermediate · 20 min

How to Host a Static Website on AWS S3 with CloudFront

By Padding · Updated 15 Nov 2026
AWS S3 · CloudFront

You will store a static site in a private S3 bucket, put CloudFront in front of it with origin access control so that only CloudFront can read the files, serve it over HTTPS, and then delete the distribution, the bucket and the access control in the right order.

On this page

S3 stores files, and CloudFront is Amazon's content delivery network. Together they host a static site with no server: S3 holds the files, and CloudFront caches them at locations near your visitors and serves them over HTTPS.

There are two ways to connect them, and one is a trap. Turning on S3's "static website hosting" and making the bucket public works, but it serves plain HTTP only, exposes your bucket to the internet, and cannot be locked to CloudFront. This tutorial uses the better design: the bucket stays private, and CloudFront reads it using origin access control (OAC), a signed request that only your distribution can make.

This costs money, and a mistake can cost a lot. S3 bills for storage and requests. CloudFront bills for data transfer out and requests (and has a free allowance whose size and rules change). A public site can be requested a huge number of times by anyone, including bots, and you pay for that traffic. Look at aws.amazon.com/s3/pricing/ and aws.amazon.com/cloudfront/pricing/ before you start, set a budget alert in AWS Billing, and do the cleanup step at the end. Also note that AWS offers CloudFront flat-rate pricing plans; a distribution subscribed to one cannot be deleted until the plan is cancelled. This tutorial uses plain pay-as-you-go pricing and does not subscribe to a plan.

Step 1 · Set names and a region

Everything below uses shell variables, so that you change a name once. The bucket name must be unique across all of AWS, so add something of your own. eu-west-1 is only an example region. CloudFront itself is global, but the bucket lives in one region:

Bash
export AWS_REGION=eu-west-1
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export BUCKET=my-site-$ACCOUNT_ID-demo
echo "$BUCKET in $AWS_REGION"

Using your account number in the bucket name makes a clash with someone else's bucket unlikely. Keep this same terminal open for the whole tutorial, because the variables disappear when you close it. When you create more variables below (OAC_ID, DIST_ID), they work the same way.

Step 2 · Create a private bucket and upload the site

Create the bucket. Outside us-east-1, S3 needs the region repeated as a location constraint:

Bash
aws s3api create-bucket --bucket "$BUCKET" --region "$AWS_REGION" \
  --create-bucket-configuration LocationConstraint="$AWS_REGION"
aws s3api put-public-access-block --bucket "$BUCKET" \
  --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true

New buckets block public access by default, and the second command states it explicitly. Do not turn it off for this design. If your region is us-east-1, leave out the --create-bucket-configuration line and its backslash.

Make a page and upload it:

Bash
mkdir -p site
cat > site/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Hello from S3 and CloudFront</title>
</head>
<body>
  <h1>Hello from S3 and CloudFront</h1>
</body>
</html>
HTML
aws s3 sync site "s3://$BUCKET" --delete

aws s3 sync copies new and changed files. --delete also removes files from the bucket that are no longer in the folder, so the bucket mirrors your folder. Check what is there:

Bash
aws s3 ls "s3://$BUCKET"

index.html is listed. A direct request to the object's S3 address now returns 403 Access Denied, which is what you want.

Step 3 · Create the origin access control

An OAC is the identity CloudFront uses when it asks S3 for a file. Create it from a small settings file. SigningBehavior set to always means CloudFront signs every request it sends to the bucket. AWS's documentation adds that with always, CloudFront talks to the S3 bucket over HTTPS, and that the other two settings (never and no-override) are for special cases, so keep always:

Bash
cat > oac.json <<JSON
{
  "Name": "$BUCKET-oac",
  "Description": "Lets CloudFront read $BUCKET",
  "SigningProtocol": "sigv4",
  "SigningBehavior": "always",
  "OriginAccessControlOriginType": "s3"
}
JSON
OAC_ID=$(aws cloudfront create-origin-access-control \
  --origin-access-control-config file://oac.json \
  --query 'OriginAccessControl.Id' --output text)
echo "$OAC_ID"

The command prints the OAC's ID, a short string of capital letters and digits. Keep it for the next step.

Step 4 · Create the CloudFront distribution

A distribution is the CloudFront configuration: where the files come from (the origin), how they are cached, and which address serves them. This one has one origin, the bucket's regional address, tied to the OAC. It redirects HTTP to HTTPS, and it uses CloudFront's managed CachingOptimized policy, whose ID is 658327ea-f89d-4fab-a63d-7e88639e58f6 in the AWS documentation. DefaultRootObject serves index.html for requests to /. PriceClass_100 limits edge locations to the cheapest group of regions, which lowers the price and may make the site slower for visitors far from them:

Bash
cat > distribution.json <<JSON
{
  "CallerReference": "$BUCKET-$(date +%s)",
  "Comment": "Static site for $BUCKET",
  "Enabled": true,
  "DefaultRootObject": "index.html",
  "PriceClass": "PriceClass_100",
  "Origins": {
    "Quantity": 1,
    "Items": [
      {
        "Id": "s3-site",
        "DomainName": "$BUCKET.s3.$AWS_REGION.amazonaws.com",
        "OriginAccessControlId": "$OAC_ID",
        "S3OriginConfig": { "OriginAccessIdentity": "" }
      }
    ]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "s3-site",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "AllowedMethods": { "Quantity": 2, "Items": ["GET", "HEAD"] },
    "Compress": true
  },
  "ViewerCertificate": { "CloudFrontDefaultCertificate": true }
}
JSON
read -r DIST_ID DIST_DOMAIN < <(aws cloudfront create-distribution \
  --distribution-config file://distribution.json \
  --query 'Distribution.[Id,DomainName]' --output text)
echo "$DIST_ID $DIST_DOMAIN"

The command prints the distribution ID and its address, such as d1234abcd.cloudfront.net. If it complains about a missing or unknown field, run aws cloudfront create-distribution --generate-cli-skeleton to see the current shape of the settings, and compare. The distribution takes several minutes to deploy to all of CloudFront's locations. Wait for it:

Bash
aws cloudfront wait distribution-deployed --id "$DIST_ID"

Step 5 · Let CloudFront, and only CloudFront, read the bucket

The bucket is private, so CloudFront needs permission, and it must be limited to this distribution. A bucket policy grants s3:GetObject to the CloudFront service, but only when the request is made on behalf of your distribution's ARN. This is the policy form that the CloudFront documentation gives for OAC:

Bash
cat > bucket-policy.json <<JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontServicePrincipalReadOnly",
      "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"
        }
      }
    }
  ]
}
JSON
aws s3api put-bucket-policy --bucket "$BUCKET" --policy file://bucket-policy.json

Without the Condition, any CloudFront distribution in any account could read your bucket. Do not remove it.

Check it worked

Bash
curl -s "https://$DIST_DOMAIN/" | grep '<title>'
curl -s -o /dev/null -w '%{http_code}\n' "https://$BUCKET.s3.$AWS_REGION.amazonaws.com/index.html"

The first command prints <title>Hello from S3 and CloudFront</title>. The second prints 403: the bucket itself is not readable directly, only through CloudFront. Plain http:// requests to the CloudFront address are redirected to HTTPS.

Troubleshooting

  • AccessDenied XML from CloudFront: the bucket policy is missing, or its AWS:SourceArn does not match the distribution (check $ACCOUNT_ID and $DIST_ID), or the origin domain name in the distribution is not the bucket's regional address. A request in the first few seconds after put-bucket-policy can also fail; retry.
  • A request for a file that is not in the bucket also returns 403, not 404, because CloudFront's permission is only to read objects (s3:GetObject), and S3 hides whether a missing key exists from callers that cannot list the bucket. If a page you uploaded returns 403, check the file name and its upload before you look at the policy.
  • NoSuchBucket from CloudFront: a typo in the origin DomainName, or the bucket is in a different region than the one in the address.
  • The site shows a previous version after you upload a change: CloudFront caches files at its edge locations, and the default time to live in this policy is 24 hours. Invalidate the changed paths: aws cloudfront create-invalidation --distribution-id "$DIST_ID" --paths "/*". The first 1,000 invalidation paths a month are free, then they are billed per path, so for regular deploys give your files version numbers or hashes in their names instead.
  • A request for /about/ returns an error while / works: DefaultRootObject only applies to the root of the site. For nested folders, use a CloudFront Function that appends index.html, or link to the full file names.
  • InvalidViewerCertificate or a certificate warning on your own domain: the default certificate covers only *.cloudfront.net. See the next step.

Step 6 · Use your own domain (optional)

For www.example.com, request a free certificate in AWS Certificate Manager in the us-east-1 region, which is the only region CloudFront reads certificates from. Validate it with the DNS record ACM gives you. Then add the domain as an alternate domain name (CNAME) in the distribution settings, select the certificate, and create a DNS CNAME record for www that points to your d....cloudfront.net address. DNS record types are covered in /tutorials/dns-records-explained-a-cname-mx-txt. This part is not scripted here because the settings differ with your DNS provider. If your domain uses Route 53, an alias record is the usual choice for the bare domain.

Step 7 · Delete everything

Run this when you finish, or the distribution and the bucket keep billing. The order matters: delete the distribution first, because deleting the bucket first leaves a distribution that points at nothing, and AWS's documentation says to delete the distribution before its S3 origin. A distribution must be disabled, and fully propagated, before it can be deleted. First read its current settings and the ETag that proves you saw the latest version, then disable it. This uses jq to switch Enabled to false:

Bash
ETAG=$(aws cloudfront get-distribution-config --id "$DIST_ID" --query ETag --output text)
aws cloudfront get-distribution-config --id "$DIST_ID" --query DistributionConfig --output json \
  | jq '.Enabled = false' > distribution-disabled.json
aws cloudfront update-distribution --id "$DIST_ID" --if-match "$ETAG" \
  --distribution-config file://distribution-disabled.json > /dev/null
aws cloudfront wait distribution-deployed --id "$DIST_ID"

Wait for the last command to return, which can take several minutes. Then delete the distribution with the new ETag, and the access control with its own ETag:

Bash
ETAG=$(aws cloudfront get-distribution-config --id "$DIST_ID" --query ETag --output text)
aws cloudfront delete-distribution --id "$DIST_ID" --if-match "$ETAG"
OAC_ETAG=$(aws cloudfront get-origin-access-control --id "$OAC_ID" --query ETag --output text)
aws cloudfront delete-origin-access-control --id "$OAC_ID" --if-match "$OAC_ETAG"

Last, the bucket. The first command permanently deletes every file in it, so check that $BUCKET is the demo bucket first (echo "$BUCKET"):

Bash
aws s3 rm "s3://$BUCKET" --recursive
aws s3api delete-bucket --bucket "$BUCKET" --region "$AWS_REGION"
rm -f oac.json distribution.json distribution-disabled.json bucket-policy.json

Check it worked

Bash
aws cloudfront list-distributions --query 'DistributionList.Items[].Id' --output text
aws s3 ls | grep "$BUCKET" || echo "bucket is gone"

Your distribution ID is no longer listed, and the bucket is gone. If the distribution delete fails with DistributionNotDisabled or a precondition error, the disable has not finished propagating or the ETag is old; run the wait again and fetch a fresh ETag. Look at the Billing pages the next day to confirm that the charges have stopped. If you added a custom domain, delete its DNS record, and delete the ACM certificate if you made one.

Next steps

  • Learn what to put in DNS for your own domain: /tutorials/dns-records-explained-a-cname-mx-txt.
  • Add the same security headers to your site: /tutorials/add-security-headers-in-nginx explains them; for CloudFront, attach a response headers policy to the distribution.
  • The AWS documentation: docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html and docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/HowToDeleteDistribution.html.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.