Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a default cache control and expires for entire S3 bucket/CloudFront

Tags:

I have an amazon S3 bucket with approximately 300K items in it that are used by a large website. I would like to set the expiration of all the objects that are served out of CloudFront from the S3 bucket so that they can be cached in the browser by the user's machine. Is there an easy way to set the cache control on all the s3 objects currently in the bucket AND most importantly set a default for the bucket so that any new items added also gain the expires and cache-control headers OR can this be done using CloudFront?

So far i have read a number of AWS documents but have found nothing:

  • http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html
  • http://docs.aws.amazon.com/cli/latest/reference/s3/index.html
like image 954
dpegasusm Avatar asked Sep 03 '14 15:09

dpegasusm


People also ask

How do I set up CloudFront Cache-Control?

Go to AWS Console and navigate to the CloudFront instance. Go to Policies - Response Headers and click on "Create response header policy" under custom policies. If you have an existing policy edit it. Add the Cache-Control header along with the max-age value you want.

Does S3 cache by default?

By default, CloudFront caches a response from Amazon S3 for 24 hours (Default TTL of 86,400 seconds).

What is the default CloudFront caching default TTL?

By default, each file automatically expires after 24 hours, but you can change the default behavior in two ways: To change the cache duration for all files that match the same path pattern, you can change the CloudFront settings for Minimum TTL, Maximum TTL, and Default TTL for a cache behavior.


1 Answers

Steps for adding cache control for existing objects in your bucket

  1. git clone https://github.com/s3tools/s3cmd
  2. Run s3cmd --configure (You will be asked for the two keys - copy and paste them from your confirmation email or from your Amazon account page. Be careful when copying them! They are case sensitive and must be entered accurately or you'll keep getting errors about invalid signatures or similar. Remember to add s3:ListAllMyBuckets permissions to the keys or you will get an AccessDenied error while testing access.)
  3. ./s3cmd --recursive modify --add-header="Cache-Control:public ,max-age= 31536000" s3://your_bucket_name/

For CloudFront you can specify Minimum TTL, Maximum TTL, and Default TTL for a cache behavior.they are basically the time for which an object can be cached on CloudFront and has nothing to do with adding an expiry header for the object i.e it doesn't mody any header

So now if you haven't added any header, then cloudfront will caches it for DEFAULT TTL. FOR MORE INFO READFOLLOWING TABLE http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html#ExpirationDownloadDist

like image 118
ashishyadaveee11 Avatar answered Sep 28 '22 09:09

ashishyadaveee11