This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.
Last Updated: 2024-11-23
What does a CDN like Cloudfront do?
You tell your web app to serve static assets (e.g. in Rails, anything under
"the assets" dir - e.g. images, JavaScript, CSS - you may need to move the Webpacker
output folder there too), from some another url - e.g. x.cloudfront.net
instead of mywebsite.com
.
Your asset file names must be finger-printed in order for cache-invalidation on the CDN to work.
With that configured, your server-side code (e.g. Rails) rewrites the URLs such that the static assets (CSS/JS/Images) etc. are from the Cloudfront instance instead of your site.
For all this to work, your assets must also have public cache headers:
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.week.to_i}"
}
To see if cache is working, curl
that url pointing to Cloudfront
# Original URL: https://www.semicolonandson.com/packs/css/application-53b44289.css
curl -I https://mycloudfrontid.cloudfront.net/packs/css/application-53b44289.css
If status 200
, it was found. If 301, it was not found.