Deploy a static website in AWS (Cloudfront + S3)
Introduuction
The architecture is very simple, an S3 bucket will have the files of the website and Cloudfront will serve the files from the bucket to the internet. Cloudfront uses a global CDN so it is fast, reliable and can scale without limitations; maybe the only problem is the update time and cache invalidation of the CDN.
The whole setup can be configured in under an hour. However, this method does not come with automatic deployment, so that has to be configured separately to sync the files in the S3 bucket.
If you want to know how this setup compares to others view my static website hosting comparison article. There, I compare all the services and methods I have used and write my opinion about them.
How to do it
There are multiple ways to do this, in this guide the bucket will be fully private and only Cloudfront will have read access so that it can serve the files. This way the users only access the website thorugh Cloudfront CDN and not through the bucket (Cloudfront acts as a cache).
Manually
Obviously, there are already guides for this on the internet so I will link them and make a summary of the steps:
- Create a normal S3 bucket and upload your website files.
- Create a CloudFront web distribution.
- Enter your Amazon S3 bucket name in the Origin Domain field.
- Under Origin access, select Origin access control settings (recommended).
- In the Origin access control dropdown list, select the OAC name and choose Create control setting.
- In the dialog box, name your control setting**.** It’s a best practice to leave the default setting Sign requests (recommended). Then, choose Create.
- CloudFront provides you with the policy statement to give OAC permission to access your Amazon S3 bucket after you create the distribution. Select Copy Policy and paste the policy in your S3 bucket policy configuration.
- To add the custom domain just go to the Cloudfront distribution dashboard and select add custom domain. Write the domain and validate the TLS certificate changing the dns records for the domain.
https://repost.aws/knowledge-center/cloudfront-serve-static-website
Automatically (with Terraform)
All this process can be completely automated using Terraform.
I was going to add the Terraform files that I used, but they are so simple that it isn’t worth it. The docs have examples of this setup and any LLM will give a usable script. Having said that, always check thouroughly a terraform script that you will execute, moreso if it was written by AI, remember that cloud providers can burn all your money if you asked them to.
Caveats
Routing won’t work like in a web server, so some rules like redirecting website.com/emaples/ to website.com/exmaples/index.html won’t work (I learned it the hard way with my Hugo website). Also, SPAs will not work until you redirect all requests to your main file.