Specifying a default root object for static website subdirectories on AWS Cloudfront
Hosting your static website on AWS S3 is a great way to serve high availability static content. On S3 it’s easy to specify a default root object for subdirectories, however you may run into some problems when trying to access this S3 bucket and its content through a Cloudfront distribution.
The problem can occur when you want to use default root objects in subdirectories on Cloudfront. Your website may generate pretty paths using subdirectories as the access URL, and have the content in these folders using an index.html file.
e.g. https://stevepapa.com/my-great-new-post/
would be expected to work the same way as: https://stevepapa.com/my-great-new-post/index.html
This works without any extra effort on S3. Cloudfront however, which is accessing the same bucket will return a 404, even if you specify a default root object on the Cloudfront distribution and the S3 bucket.
There’s a clever little way to get these flowing through to the Cloudfront distribution, and it involves changing the source origin from the one that Cloudfront presents to you by default.
When selecting the origin source Cloudfront will show you a list of S3 buckets.
Instead of setting the source from the bucket shown in the dropdown list, you’ll need to grab the static web hosting endpoint for that resource from its S3 settings page and pop it in manually.
Using the static source for the Cloudfront distribution origin means any request to that distribution will be using the S3’s root object lookup, and your 404 responses should disappear as the references flow through.