This week while optimizing a website for performance one of the issues that came up was that the cache headers were not set for assets served using CloudFront.
CloudFront does not allow Cache-Control headers to be set but allows the use of the Origin Cache Headers pulled from Amazon S3. Most assets uploaded to S3 over the last three years did not have the headers set 😱, and on Amazon S3 console you can only add headers to one object at a time, so had to use AWS CLI to add headers to all objects in one go.
aws s3 cp s3://bucket-name/ s3://bucket-name/ --metadata-directive REPLACE --recursive --cache-control max-age=2592000
Max-age value is in seconds: 2592000 seconds = 30 days
This project uses Laravel, so I had to update the settings for the Cache-Control header to be set correctly for all new objects uploaded moving forward.
To set the Default Cache-Control header update the S3 settings within config/filesystems.php file as follow:
's3' => [ 'driver' => 's3', 'key' => env('AMAZON_S3_KEY'), 'secret' => env('AMAZON_S3_SECRET'), 'region' => env('AMAZON_S3_REGION'), 'bucket' => env('AMAZON_S3_BUCKET'), 'options' => [ 'CacheControl' => 'max-age=2592000', // 2592000 seconds = 30 days ] ],
With the default CacheControl settings defined all new objects uploaded to Amazon S3 will have the Cache-Control header set to max-age=2592000. These settings can be overridden for an individual object if needed.
This is my first post on Dev.to. Very cool! 😎