Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimizing asset delivery with immutable cache-control on Cloudflare R2 #136

Open
rednafi opened this issue Sep 16, 2024 · 0 comments
Open

Comments

@rednafi
Copy link
Owner

rednafi commented Sep 16, 2024

I'm adding cache-control headers to some assets on rednafi.com, like CSS and images, to make them immutable and cache them for a long time. These assets don’t change much, and making them immutable will save on R2 quota since they won't be fetched from the bucket on every request.

  • Set up Cloudflare Cache in front of the site (already done).
  • Configure AWS CLI (CF R2 is AWS S3 compatible, so setting this up is easy).
  • Reupload the targeted assets. You can’t set the cache-control header on an existing object, so reuploading is necessary. This command uploads all files in the ./static/images/home directory to the bucket named blog:
aws s3 cp ./static/images/home s3://blog/static/images/home --recursive --metadata-directive REPLACE --cache-control "public, max-age=315360000, immutable" --endpoint-url=https://f2c208344e8adb0cf3ea1e48dccf7218.r2.cloudflarestorage.com
  • Check the status of a particular file:
aws s3api head-object --bucket blog --key static/images/home/cover.png --endpoint-url=https://f2c208344e8adb0cf3ea1e48dccf7218.r2.cloudflarestorage.com

This will return:

{
    "AcceptRanges": "bytes",
    "LastModified": "2024-09-16T18:44:03+00:00",
    "ContentLength": 72708,
    "ETag": "\"47e8d2ad91977193a0efa6466a3990eb\"",
    "CacheControl": "public, max-age=315360000, immutable",
    "ContentType": "image/png",
    "Metadata": {}
}
  • Finally, verify the cache-control by fetching the asset:
curl -I https://blob.rednafi.com/static/images/home/cover.png

It should return:

HTTP/2 200 
date: Mon, 16 Sep 2024 19:25:36 GMT
content-type: image/png
content-length: 72708
cache-control: public, max-age=315360000, immutable
etag: "47e8d2ad91977193a0efa6466a3990eb"
last-modified: Mon, 16 Sep 2024 18:44:03 GMT
cf-cache-status: EXPIRED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant