Hosting a static site on S3 and CloudFront with HTTPS
A private S3 bucket behind CloudFront with Origin Access Control, an ACM certificate from us-east-1 validated by hand at a non-Route 53 registrar, clean URLs with a CloudFront Function and a deploy script that invalidates the cache.
A static site doesn't need a server. HTML, CSS and a few images in an S3 bucket, CloudFront in front for HTTPS and caching, and the bill for a small site is close to zero. The old way of doing this was to turn on "static website hosting" on a public bucket. Please don't. The bucket stays private and only CloudFront can read it.
In this blog we will set that up in Terraform: a private bucket, CloudFront with Origin Access Control (OAC), an ACM certificate in us-east-1, clean URLs, a 404 page, and a deploy script that syncs files and invalidates the cache. It's a beginner tutorial. You need an AWS account (see Setting up a new AWS account safely), Terraform and the AWS CLI, and a domain where you can add DNS records.
Versions I used: Terraform 1.17.1, AWS provider 6.73.0, AWS CLI 2.38.6. Prices are from the AWS Price List API on 19 November 2026. I ran terraform validate and tested the CloudFront Function locally, but I didn't apply this to an account while writing.
How the pieces fit
browser --HTTPS--> CloudFront (docs.example.com, ACM cert from us-east-1)
|
| viewer-request: CloudFront Function adds index.html
|
+--SigV4 signed (OAC)--> S3 bucket (private, ap-south-1)
The bucket can live in any region. I put it in ap-south-1 because that's where everything else of mine is. The certificate can't, CloudFront only reads certificates from us-east-1. That's why there are two provider blocks.
terraform {
required_version = ">= 1.10"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
provider "aws" {
alias = "us_east_1"
region = "us-east-1"
}
variable "domain" {
type = string
default = "docs.example.com"
}
variable "bucket_name" {
type = string
default = "docs-example-com-site"
}
The private bucket
Block all public access and turn off ACLs. Nothing here makes the bucket readable from the internet.
resource "aws_s3_bucket" "site" {
bucket = var.bucket_name
}
resource "aws_s3_bucket_public_access_block" "site" {
bucket = aws_s3_bucket.site.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_ownership_controls" "site" {
bucket = aws_s3_bucket.site.id
rule {
object_ownership = "BucketOwnerEnforced"
}
}
The bucket policy lets the CloudFront service read objects, but only when the request comes from our distribution. The AWS:SourceArn condition is the important line. Without it, any CloudFront distribution in any account could point at your bucket.
data "aws_iam_policy_document" "site" {
statement {
sid = "AllowCloudFrontRead"
actions = ["s3:GetObject"]
resources = ["${aws_s3_bucket.site.arn}/*"]
principals {
type = "Service"
identifiers = ["cloudfront.amazonaws.com"]
}
condition {
test = "StringEquals"
variable = "AWS:SourceArn"
values = [aws_cloudfront_distribution.site.arn]
}
}
}
resource "aws_s3_bucket_policy" "site" {
bucket = aws_s3_bucket.site.id
policy = data.aws_iam_policy_document.site.json
depends_on = [aws_s3_bucket_public_access_block.site]
}
If you've seen Origin Access Identity (OAI) in older posts, OAC replaces it. OAI still works for old distributions but new ones should use OAC, it signs requests with SigV4 and works with SSE-KMS buckets.
The certificate, validated by hand
My DNS for fenixara.com is at GoDaddy, not Route 53, so I can't let Terraform create the validation record. If yours is in Route 53 you can add an aws_route53_record and skip the manual step. For everyone else, Terraform requests the certificate, prints the CNAME, and waits.
resource "aws_acm_certificate" "site" {
provider = aws.us_east_1
domain_name = var.domain
validation_method = "DNS"
lifecycle {
create_before_destroy = true
}
}
output "acm_validation_records" {
value = {
for o in aws_acm_certificate.site.domain_validation_options : o.domain_name => {
name = o.resource_record_name
type = o.resource_record_type
value = o.resource_record_value
}
}
}
resource "aws_acm_certificate_validation" "site" {
provider = aws.us_east_1
certificate_arn = aws_acm_certificate.site.arn
}
The trick is to apply in two steps. First only the certificate, so you get the record:
terraform init
terraform apply -target=aws_acm_certificate.site
terraform output acm_validation_records
Add that CNAME at your registrar. Keep it there forever, ACM uses the same record to renew the certificate every year. Then run a full terraform apply. The validation resource waits until ACM sees the record, and the distribution is created after it. At GoDaddy, paste the name without the domain part on the end, their form appends it for you. See, this one trips people up because the record looks right and validation still hangs.
Public ACM certificates are actually free, by the way. You pay nothing for the cert or the renewals.
CloudFront with OAC
I use the managed cache policy and the managed security headers policy instead of writing my own. They are looked up by name, so no magic IDs in the code.
resource "aws_cloudfront_origin_access_control" "site" {
name = var.bucket_name
origin_access_control_origin_type = "s3"
signing_behavior = "always"
signing_protocol = "sigv4"
}
data "aws_cloudfront_cache_policy" "optimized" {
name = "Managed-CachingOptimized"
}
data "aws_cloudfront_response_headers_policy" "security" {
name = "Managed-SecurityHeadersPolicy"
}
resource "aws_cloudfront_function" "index" {
name = "${replace(var.bucket_name, ".", "-")}-index"
runtime = "cloudfront-js-2.0"
publish = true
code = file("${path.module}/index-rewrite.js")
}
resource "aws_cloudfront_distribution" "site" {
enabled = true
is_ipv6_enabled = true
http_version = "http2and3"
aliases = [var.domain]
default_root_object = "index.html"
price_class = "PriceClass_200"
comment = var.domain
origin {
origin_id = "s3-site"
domain_name = aws_s3_bucket.site.bucket_regional_domain_name
origin_access_control_id = aws_cloudfront_origin_access_control.site.id
}
default_cache_behavior {
target_origin_id = "s3-site"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["GET", "HEAD"]
cached_methods = ["GET", "HEAD"]
compress = true
cache_policy_id = data.aws_cloudfront_cache_policy.optimized.id
response_headers_policy_id = data.aws_cloudfront_response_headers_policy.security.id
function_association {
event_type = "viewer-request"
function_arn = aws_cloudfront_function.index.arn
}
}
custom_error_response {
error_code = 403
response_code = 404
response_page_path = "/404.html"
error_caching_min_ttl = 60
}
restrictions {
geo_restriction {
restriction_type = "none"
}
}
viewer_certificate {
acm_certificate_arn = aws_acm_certificate_validation.site.certificate_arn
ssl_support_method = "sni-only"
minimum_protocol_version = "TLSv1.2_2021"
}
}
output "distribution_id" {
value = aws_cloudfront_distribution.site.id
}
output "cloudfront_domain" {
value = aws_cloudfront_distribution.site.domain_name
}
output "bucket_name" {
value = aws_s3_bucket.site.bucket
}
A few choices in there. PriceClass_200 because my readers are mostly in India and price class 100 leaves out the Indian edge locations. The 403 error response is mapped to a 404 page because the policy only grants s3:GetObject. When a key is missing, S3 says 403 and not 404 since CloudFront isn't allowed to list the bucket. I prefer it that way: no listing permission, and the visitor still sees a proper not found page.
Point acm_certificate_arn at the validation resource, not the certificate. That makes Terraform wait for validation before it tries to attach the cert, otherwise CloudFront rejects a certificate that is still pending.
Once apply finishes, add a CNAME from docs.example.com to the cloudfront_domain output at your registrar. For an apex domain like example.com you need Route 53 (alias record) or a registrar that supports ALIAS/ANAME, a plain CNAME at the apex is not allowed.
Clean URLs with a CloudFront Function
default_root_object only works for the root. A request for /about/ would go to S3 as the key about/, which doesn't exist. Static site generators write about/index.html, so a tiny function rewrites the URI on the way in.
function handler(event) {
var request = event.request;
var uri = request.uri;
if (uri.endsWith('/')) {
request.uri = uri + 'index.html';
} else if (!uri.split('/').pop().includes('.')) {
request.uri = uri + '/index.html';
}
return request;
}
I don't have node on this Mac, so I tested it with macOS's own JavaScript runner, osascript -l JavaScript, by appending a few calls to the file. The output was what I wanted:
/ -> /index.html
/about -> /about/index.html
/about/ -> /about/index.html
/css/site.3f2a.css -> /css/site.3f2a.css
/blog/post-1 -> /blog/post-1/index.html
You can also test it in the console or with aws cloudfront test-function once it exists. The first 2 million function runs a month are free and after that it's $0.10 per million, which for a small site is basically nothing.
Deploying and invalidating
The deploy is two aws s3 sync runs and one invalidation. Files with a hash in the name can be cached for a year. HTML must be checked every time, otherwise people see an old page pointing at CSS that no longer exist.
#!/usr/bin/env bash
# Usage: ./deploy.sh ./public
set -euo pipefail
SRC=${1:-./public}
BUCKET=$(terraform output -raw bucket_name)
DIST=$(terraform output -raw distribution_id)
aws s3 sync "$SRC" "s3://$BUCKET" --delete \
--exclude "*.html" \
--cache-control "public, max-age=31536000, immutable"
aws s3 sync "$SRC" "s3://$BUCKET" --delete \
--exclude "*" --include "*.html" \
--cache-control "public, max-age=0, must-revalidate"
aws cloudfront create-invalidation \
--distribution-id "$DIST" \
--paths "/*" \
--query 'Invalidation.{id: Id, status: Status}' \
--output table
The --exclude filters also apply to --delete, so the first run doesn't remove HTML and the second doesn't touch the assets. The first 1,000 invalidation paths each month are free and /* counts as one path, so invalidating everything on each deploy costs nothing unless you deploy hundreds of times a month.
If you build the site in GitHub Actions (GitHub Actions from zero), the same script runs as a step. Give that job a role that can only s3:PutObject, s3:DeleteObject and s3:ListBucket on this one bucket plus cloudfront:CreateInvalidation on this one distribution. IAM explained by writing policies shows how to write that.
Checking it works
curl -sI https://docs.example.com/ | grep -i -E "^HTTP|x-cache|strict-transport"
curl -sI https://docs.example.com/does-not-exist | head -1
curl -sI "https://$(terraform output -raw bucket_name).s3.ap-south-1.amazonaws.com/index.html" | head -1
The first should show HTTP/2 200, an x-cache header (Miss the first time, Hit after) and the HSTS header from the managed policy. The second should be a 404. The third goes straight to S3 and must be a 403. If that one returns 200, your bucket is public and something above was skipped.
What it costs
Mumbai prices on 19 November 2026. S3 Standard is $0.025 per GB-month, PUTs are $0.005 per 1,000 and GETs $0.004 per 10,000. Transfer from S3 to CloudFront is free. CloudFront to viewers in India is $0.109 per GB for the first 10 TB and $0.012 per 10,000 HTTPS requests, but the always-free tier covers 1 TB and 10 million requests a month.
So a 2 GB site that serves 50 GB and half a million requests a month costs about five cents for storage, and the CloudFront part sits inside the free tier. Without the free tier it would be about $5.45 for transfer and $0.60 for requests.
CloudFront now also sells flat-rate plans per distribution, a Free plan with 1 million requests and 100 GB a month and a Pro plan at $15 a month, with no overage charges. For a small site I'd stay on pay as you go. The flat-rate plan makes more sense once a traffic spike or a bot crawl is what you're worried about.
My own blog itself doesn't use any of this. Ghost is dynamic, so it runs behind Caddy with Let's Encrypt on the EC2 box (Automatic HTTPS and www redirects for a Ghost blog using Caddy). For docs, a landing page or a portfolio though, S3 and CloudFront is what I'd reach for first.