Host a static website on S3 and CloudFront with HTTPS
Serve a static site from a private S3 bucket through CloudFront on your own domain with an ACM certificate. Visitors get HTTPS and a cache close to them, and the bucket itself is never public.
Browser
Route 53
CloudFront
Private S3 bucket
How it works
Why not a public bucket
S3 website hosting works, but it needs a public bucket and it does not serve HTTPS on your own domain. Public buckets are also where files that were never meant to be shared end up. Putting CloudFront in front lets the bucket stay private while the site is still open to everyone.
Create the private bucket
The bucket blocks all public access, encrypts files at rest with a KMS key that you own and keeps old versions of each file. Versioning means a deploy that overwrites the wrong file can be undone.
Issue the certificate
ACM issues a free certificate once it sees a DNS record that proves you own the domain, and the configuration adds that record to your Route 53 zone. The mistake people make: CloudFront only accepts certificates created in us-east-1. This configuration uses a second provider for that, so the bucket can live in any region.
Put CloudFront in front
Origin access control lets CloudFront sign its requests to S3, and the bucket policy allows reads only from this one distribution. The key policy lets that same distribution decrypt the files, and without it every page returns 403. To add a web application firewall, pass its ARN in web_acl_arn. It is off by default because a WAF has a fixed monthly fee. Plain HTTP requests are redirected to HTTPS. Requests for a file that does not exist return your 404.html page.
Upload and refresh
Copy the built site into the bucket with aws s3 sync, using a role that has kms:GenerateDataKey and kms:Decrypt on the key, then create a CloudFront invalidation for /* so visitors get the new files. One thing to know: CloudFront serves index.html for the root address only. A link to /about/ does not find /about/index.html unless your site generator writes flat files or you add a small CloudFront function to rewrite the path.
What you set
domain_name
Domain the site is served on For example www.example.com
zone_id
Route 53 hosted zone that contains the domain For example Z0123456789ABCDEFGHIJ
bucket_name
Globally unique bucket name For example example-com-site
web_acl_arn
Optional WAF web ACL with CLOUDFRONT scope, leave unset for no WAF For example arn:aws:wafv2:us-east-1:111122223333:global/webacl/site/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
What it costs to run
About $2 to $6 a month for a small site: $0.50 for the hosted zone, $1 for the KMS key, a few cents of S3 storage, and CloudFront traffic that usually stays inside its free allowance. The certificate is free. Heavy traffic or large downloads are what raise it. Estimate.
The configuration
# A static site in a private S3 bucket, served over HTTPS by CloudFront.
#
# What this creates:
# - a KMS key of your own that encrypts the site files
# - a private S3 bucket, encrypted with that key, that holds the site files
# - an ACM certificate for your domain, validated through Route 53
# - a CloudFront distribution that reads the bucket with origin access control
# - DNS records that point the domain at the distribution
terraform {
required_version = ">= 1.6.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.region
}
# CloudFront only accepts certificates from us-east-1, whatever region the
# bucket is in.
provider "aws" {
alias = "us_east_1"
region = "us-east-1"
}
variable "region" {
description = "AWS region for the bucket."
type = string
default = "us-east-1"
}
variable "domain_name" {
description = "Domain the site is served on, for example www.example.com."
type = string
}
variable "zone_id" {
description = "ID of the Route 53 hosted zone that contains domain_name."
type = string
}
variable "bucket_name" {
description = "Name for the S3 bucket. Bucket names are global, so pick something unique."
type = string
}
variable "web_acl_arn" {
description = "ARN of a WAF web ACL to put in front of the site. It must have CLOUDFRONT scope, which means it is created in us-east-1. Leave null for no WAF."
type = string
default = null
}
data "aws_caller_identity" "current" {}
# --- Bucket ------------------------------------------------------------------
resource "aws_s3_bucket" "site" {
bucket = var.bucket_name
}
# The bucket stays private. Visitors never talk to S3 directly.
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
}
# A key you own, in the same region as the bucket. Its policy is set further
# down, next to the bucket policy, because both name the distribution.
resource "aws_kms_key" "site" {
description = "Encrypts the site files in ${var.bucket_name}"
enable_key_rotation = true
# Days AWS waits before deleting the key after a destroy. The site files
# can be built and uploaded again, so the shortest wait is enough.
deletion_window_in_days = 7
}
resource "aws_kms_alias" "site" {
name = "alias/${var.bucket_name}"
target_key_id = aws_kms_key.site.key_id
}
resource "aws_s3_bucket_server_side_encryption_configuration" "site" {
bucket = aws_s3_bucket.site.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.site.arn
}
# One data key per bucket instead of one KMS request per file, which keeps
# the KMS request cost low.
bucket_key_enabled = true
}
}
# Versioning lets you get back a file that a bad deploy overwrote.
resource "aws_s3_bucket_versioning" "site" {
bucket = aws_s3_bucket.site.id
versioning_configuration {
status = "Enabled"
}
}
# --- Certificate -------------------------------------------------------------
resource "aws_acm_certificate" "site" {
provider = aws.us_east_1
domain_name = var.domain_name
validation_method = "DNS"
lifecycle {
create_before_destroy = true
}
}
resource "aws_route53_record" "validation" {
for_each = {
for option in aws_acm_certificate.site.domain_validation_options : option.domain_name => {
name = option.resource_record_name
type = option.resource_record_type
record = option.resource_record_value
}
}
zone_id = var.zone_id
name = each.value.name
type = each.value.type
records = [each.value.record]
ttl = 60
allow_overwrite = true
}
# Waits until ACM has seen the DNS record and issued the certificate.
resource "aws_acm_certificate_validation" "site" {
provider = aws.us_east_1
certificate_arn = aws_acm_certificate.site.arn
validation_record_fqdns = [for record in aws_route53_record.validation : record.fqdn]
}
# --- CloudFront --------------------------------------------------------------
resource "aws_cloudfront_origin_access_control" "site" {
name = var.bucket_name
description = "CloudFront access to ${var.bucket_name}"
origin_access_control_origin_type = "s3"
signing_behavior = "always"
signing_protocol = "sigv4"
}
data "aws_cloudfront_cache_policy" "optimized" {
name = "Managed-CachingOptimized"
}
resource "aws_cloudfront_distribution" "site" {
enabled = true
is_ipv6_enabled = true
comment = var.domain_name
aliases = [var.domain_name]
default_root_object = "index.html"
http_version = "http2and3"
# North America and Europe only, the cheapest class. Use PriceClass_All if
# most visitors are elsewhere.
price_class = "PriceClass_100"
# A WAF costs a fixed monthly fee, so it is opt-in. Null means none.
web_acl_id = var.web_acl_arn
origin {
origin_id = "s3"
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"
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
}
# A private bucket answers 403 for a missing file. Show the 404 page instead.
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"
}
}
# Only this one distribution may read the bucket. Without the SourceArn
# condition, any CloudFront distribution in any account could.
data "aws_iam_policy_document" "bucket" {
statement {
sid = "CloudFrontRead"
effect = "Allow"
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.bucket.json
depends_on = [aws_s3_bucket_public_access_block.site]
}
# The files are encrypted with your key, so CloudFront also needs permission
# to decrypt. Without the second statement every page returns 403.
data "aws_iam_policy_document" "key" {
# Keeps the usual rule that IAM policies in this account decide who may use
# and manage the key. Whoever uploads the site needs kms:GenerateDataKey
# and kms:Decrypt on it.
statement {
sid = "AccountAdministersKey"
effect = "Allow"
actions = ["kms:*"]
resources = ["*"]
principals {
type = "AWS"
identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
}
}
# Decrypt only, and only for this one distribution.
statement {
sid = "CloudFrontDecrypt"
effect = "Allow"
actions = ["kms:Decrypt"]
resources = ["*"]
principals {
type = "Service"
identifiers = ["cloudfront.amazonaws.com"]
}
condition {
test = "StringEquals"
variable = "AWS:SourceArn"
values = [aws_cloudfront_distribution.site.arn]
}
}
}
resource "aws_kms_key_policy" "site" {
key_id = aws_kms_key.site.id
policy = data.aws_iam_policy_document.key.json
}
# --- DNS ---------------------------------------------------------------------
resource "aws_route53_record" "site_a" {
zone_id = var.zone_id
name = var.domain_name
type = "A"
alias {
name = aws_cloudfront_distribution.site.domain_name
zone_id = aws_cloudfront_distribution.site.hosted_zone_id
evaluate_target_health = false
}
}
resource "aws_route53_record" "site_aaaa" {
zone_id = var.zone_id
name = var.domain_name
type = "AAAA"
alias {
name = aws_cloudfront_distribution.site.domain_name
zone_id = aws_cloudfront_distribution.site.hosted_zone_id
evaluate_target_health = false
}
}
output "bucket_name" {
description = "Upload the built site here, for example with aws s3 sync."
value = aws_s3_bucket.site.bucket
}
output "distribution_id" {
description = "Use this to invalidate the cache after a deploy."
value = aws_cloudfront_distribution.site.id
}
output "site_url" {
description = "Address of the site."
value = "https://${var.domain_name}"
}
Works with OpenTofu 1.6 or later, and with Terraform. Read it before you apply it: it creates real resources in your account.