Set cache control on S3 objects using the AWS CLI
Cache-control can be set on S3 bucket objects.
Setting cache control using aws s3 cp
An object’s metadata may only be changed by overwriting it using the metadata-directive
flag.
Single file:
1aws s3 cp s3://bucket/example.txt s3://s3-bucket/file.txt \
2 --metadata-directive REPLACE \
3 --cache-control max-age=86400
All files:
1aws s3 cp s3://bucket/ s3://bucket/ \
2 --metadata-directive REPLACE \
3 --cache-control max-age=86400 \
4 --recursive
All image files / specific file extensions
1aws s3 cp s3://bucket/ s3://bucket/ \
2 --metadata-directive REPLACE \
3 --cache-control max-age=86400 \
4 --exclude "*" \
5 --include "*.jpg" \
6 --include "*.gif" \
7 --include "*.webp" \
8 --recursive
Setting cache control for websites served by AWS CloudFront
CloudFront is a CDN service provided by AWS. The max-age
directive sets the browser caching age in seconds while another directive named s-maxage
sets the CloudFront caching in seconds.
Choosing from the examples above, add s-maxage=86400
to the --cache-control
flag for all objects in a bucket.
1aws s3 cp s3://bucket/ s3://bucket/ \
2 --metadata-directive REPLACE \
3 --cache-control max-age=86400,s-maxage=86400 \
4 --recursive
Setting cache control using aws s3 sync
Warning: Using this option only sets cache headers upon initial sync. The cp command will need to be used to replace headers on existing S3 objects.
1aws s3 sync /path s3://bucket/ \
2 --cache-control max-age=86400,s-maxage=86400