CloudFront caching static website hosted in S3 bucket

Last modified date

Comments: 0

The problem

If you are using an S3 bucket to host a static website and have a CloudFront distribution to serve the website, you may have noticed that after deleting all of the website files in your S3 bucket, the website still loads when navigating to the domain.

This is because CloudFront caches the website files for up to 24 hours after you delete the files in S3.

This means that even if you put new website files in the S3 bucket, the old website will be served to users.

This is not ideal.

The Solution

There are two ways of solving this problem, invalidating the caches or object versioning.

Invalidating the caches

Invalidating the caches is the quick and dirty way of doing things.

Navigate to CloudFront in the AWS Console and then click on the CloudFront distribution that you want to invalidate.

Click on the Invalidations tab.

Select Create Invalidation.

Then enter /* in the Object Paths. This will remove all the S3 files cached in CloudFront.

Click Invalidate.

Then wait for the status to complete.

Now if you navigate to your domain, CloudFront will serve up an error instead of your cached website.

Note that AWS allows only a certain number of free invalidations per month. Check the exact value to avoid charges to your account.

Object Versioning

Alternatively, you can use Object Versioning so that CloudFront can automatically detect when you upload new files to CloudFront.

More information can be found here:

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/UpdatingExistingObjects.html

References

https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serving-outdated-content-s3/

https://aws.amazon.com/about-aws/whats-new/2015/05/amazon-cloudfront-makes-it-easier-to-invalidate-multiple-objects/

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/UpdatingExistingObjects.html

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.