packethound.io

CloudFront Setup

Setting up CloudFront with S3 for static sites - lessons learned.

The Challenge

Deploying a Hugo site to S3 + CloudFront isn’t as straightforward as it should be. Here’s what actually works.

Required Components

1
2
3
4
5
# S3 bucket (regular, not website endpoint)
aws s3 mb s3://packethound.io

# CloudFront distribution with OAC
# Origin Access Control (not the legacy OAI)

The Missing Pieces

Default Root Object

Set to index.html - only works for root URL though.

CloudFront Function

Required for directory handling:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function handler(event) {
    var request = event.request;
    var uri = request.uri;
    
    if (uri.endsWith('/')) {
        request.uri += 'index.html';
    } else if (!uri.includes('.')) {
        request.uri += '/index.html';
    }
    
    return request;
}

Bucket Policy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Service": "cloudfront.amazonaws.com"},
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::packethound.io/*",
    "Condition": {
      "StringEquals": {
        "AWS:SourceArn": "arn:aws:cloudfront::ACCOUNT:distribution/DIST_ID"
      }
    }
  }]
}

Cache Settings

Deployment

Hugo’s built-in S3 deployment works great:

1
hugo deploy --target s3

Much simpler than custom scripts.

Tags: