Subdirectories on AWS Cloudfront when hosting on S3

July 22, 2019

Scenario: You are hosting a S3 website, you want to apply SSL to it, so you used Cloudfront to create a HTTPs endpoint. However your website features subdirectories such as /blog. With Cloudfront this would be an issue since it maps to the S3 bucket and thus does not follow S3 logic when mapping subdirectories. So even if /blog on S3 has a index.html file, the route on Cloudfront would return a Object not found XML document.

There are two ways to fix this:

Map S3 endpoint instead of the bucket name in Cloudfront

When creating the Cloudfront distribution for the web, AWS will auto fill S3 bucket names.


Instead of letting AWS autofill the S3 bucket. Just paste in the static S3 bucket endpoint.

S3 Endpoint

So if you had www.mysite.com.s3.amazonaws.com in Cloudfront. Replace it with www.mysite.com.s3-website-us-west-2.amazonaws.com from S3.

Use AWS Lambda to map routes to Cloudfront.

The other way recommended by AWS Compute Blog is to used Lambda functions to implement default indexes in directories. The link covers the process fairly well bar some UI changes.

Farhad Agzamov

Written by Farhad Agzamov who lives and works in London building things. You can follow him on Twitter and check out his github here