Host Website on S3 thru CloudFront
In this post, I am going to describe how to host a website on S3, allowing the access from CloudFront for faster content distribution.
user -> CloudFront -> S3
Create Bucket on S3
% mkdir web && cd web
% echo 'Hello, World!' > index.html
% aws s3 mb s3://YOUR_BUCKET_NAME
% aws s3 cp index.html s3://YOUR_BUCKET_NAME
Confirm that you cannot access the bucket directly.
% curl https://s3.amazonaws.com/YOUR_BUCKET_NAME/index.html
AccessDenied
Create Distribution on CloudFront
Console > CloudFront > Create Distribution > Get Started >
- Origin Domain Name: YOUR_BUCKET_NAME
- Restrict Bucket Access: Yes
- Origin Access Identity: Create a New Identity
- Grant Read Permissions on Bucket: Yes, Update Bucket Policy
- Default Root Object: index.html
> Create Distribution
This will take a few minutes.
Access
% aws cloudfront list-distributions | jq -r '.DistributionList.Items[0].DomainName'
xxxxxxxxxxxxx.cloudfront.net
% curl xxxxxxxxxxxxx.cloudfront.net
Hello, World!
Modify Content
% echo 'foo' > index.html
% aws s3 cp index.html s3://YOUR_BUCKET_NAME
% curl xxxxxxxxxxxxx.cloudfront.net
Hello, World!
It will take some time for the cache to be updated.
You can clear the cache by invalidating the objects on CloudFront.
% aws cloudfront list-distributions | jq -r '.DistributionList.Items[0].Id'
yyyyyyyyyyyyyyyyyyyyy
% aws cloudfront create-invalidation --distribution-id= yyyyyyyyyyyyyyyyyyyyy --path '/'
% curl xxxxxxxxxxxxx.cloudfront.net
foo
Comments
Post a Comment