DEV Community

Cover image for CloudFront Caching for AWS S3 Objects
Moin Akhter
Moin Akhter

Posted on

CloudFront Caching for AWS S3 Objects

In this blog, we will learn about caching s3 objects by using another AWS service called Cloudfront.

Storing images and files on s3 is a very common and cost-effective solution. But cost-effectiveness is not everything but the performance of the object that your client accessing does also matter. Now by default, AWS uses very good approaches to give back your object (In the S3 world any file or image that you upload on it is an object). Now we can also optimize by caching the most frequently accessed object on CDN servers managed by AWS. Now for this purpose, AWS gives us another service called Cloud Front.

Now let's see how we can create an s3 bucket and use Cloud Front in order to cache our objects.

CREATE YOU BUCKET FIRST:-

  1. Go to s3.
  2. Click on Create Bucket.
  3. Give an appropriate name for your bucket.
  4. Leave your bucket as private as we will use cloud front in order to get objects.
  5. Enable version if you want versioning.
  6. Then click on the Create Bucket button.

CREATE A CLOUD FRONT FOR CACHING PURPOSE:-

  1. Go to cloud front service.
  2. Click on Create Distribution.
  3. For the Origin domain select the bucket name for which you want to add this distribution.
  4. For Origin access select Origin access control settings (recommended). A dropdown will appear click on create access control setting button. Select recommended for Signing behavior and also check the do not override header check box, select origin type as s3, and click create.
  5. For Web Application Firewall (WAF) select Enable Security Protection for security purposes.
  6. For the Default root object use any default image name that will be shown when you hit the base URL of this distribution.
  7. Click on the Create and Copy policy. We will attach this policy to the s3 bucket which will block everyone from accessing objects of the bucket and only allow this distribution to access s3 objects on behalf of the user which is a kind of an extra layer of security.
  8. Go to your intended bucket and in the Permissions tab go to Bucket Policy paste the copied policy of Cloud Front distribution there and click on save changes.
  9. Now upload an image with the same name and extension that you set for the Default root object while creating the cloud front distribution. Now go to your cloud front distribution and go to the General tab. In general tab you will be able to see the Distribution domain name. Copy this Distribution domain name and hit on your browser you will be able to see the Default root object on the base URL. That's it now you can access your objects on "distributionUrl/objectName". Object will also be cached on some CDN server by aws so whenever you access this file aws will give you back the cached file in order to decrease latency.

Top comments (0)