Apply Cache Control Using AWS Console
To change Cache Control for all objects in a bucket, open the bucket in the console, select all the folders and files and click on More > Change metadata. In the Change Metadata section, set Cache Control as the header and the value as max-age=’value in seconds’.
Apply Cache Control from Command Line
Cache Control metadata can also be changed from the command line. The command line tool can be used to add or modify metadata of objects. However, note that the metadata can only be added or modified by copying the object to itself. Below is a snippet of the command.
-- single object
aws s3 cp s3://s3-bucket/file.txt s3://s3-bucket/file.txt --metadata-directive REPLACE --cache-control max-age=86400
--all files in a bucket (use the recursive flag)
aws s3 cp s3://s3-bucket/ s3://s3-bucket/ --metadata-directive REPLACE --recursive --cache-control max-age=86400
--only images
aws s3 cp s3://s3-bucket/ s3://s3-bucket/ --metadata-directive REPLACE
--exclude "*" --include "*.jpg" --include "*.gif" \ --include "*.png"
--recursive --cache-control max-age=86400
Note that the recursive keyword needs to be used to apply the command to all files in the bucket.
Apply Cache Control for Websites served from Cloudfront
Cloudfront can be used as a CDN to serve content from the edge locations. The Cache Control can be set for both browser / proxy and Cloudfront by using max-age and s-max-age directives. When set, the s-max-age directive applies caching time for object in the browser or proxy and the max-age directive applies caching time in Cloudfront.
-- single object
aws s3 cp s3://s3-bucket/file.txt s3://s3-bucket/file.txt --metadata-directive REPLACE --cache-control max-age=86400,s-maxage=86400
--all files in a bucket (use the recursive flag)
aws s3 cp s3://s3-bucket/ s3://s3-bucket/ --metadata-directive REPLACE --recursive --cache-control max-age=86400,s-maxage=86400
--only images
aws s3 cp s3://s3-bucket/ s3://s3-bucket/ --metadata-directive REPLACE
--exclude "*" --include "*.jpg" --include "*.gif" \ --include "*.png"
--recursive --cache-control max-age=86400,s-maxage=86400