Enable Caching on Sourcehut Pages and Cache Busting for Zola Sites

For websites hosted on sourcehut pages it is possible to enable caching of files matching given globs via a site configuration file:

{
    "fileConfigs": [
        { "glob": "*.css", "options": { "cacheControl": "max-age=31536000" } },
        { "glob": "*.js", "options": { "cacheControl": "max-age=31536000" } },
        { "glob": "*.png", "options": { "cacheControl": "max-age=31536000" } },
        { "glob": "*.jpg", "options": { "cacheControl": "max-age=31536000" } },
        { "glob": "*.webp", "options": { "cacheControl": "max-age=31536000" } },
        { "glob": "*.svg", "options": { "cacheControl": "max-age=31536000" } },
        { "glob": "*.ttf", "options": { "cacheControl": "max-age=31536000" } },
        { "glob": "*.woff", "options": { "cacheControl": "max-age=31536000" } },
        { "glob": "*.woff2", "options": { "cacheControl": "max-age=31536000" } }
    ]
}

Deploy the file with the hut CLI tool:

hut pages publish -d talfus-laddus.de --site-config siteconfig.json site.tar.gz

Now that files are cached by the browser for a long time (e.g. 365 days), what happens if a file, say style.css changes? The website visitor would only get the new style after a year (or if he/she force reloads the page). To avoid this scenario one could rename style.css to style-v1.css which would not be found in the cache by the browser and hence will be requested from the server. This technique is called cache busting.

Renaming files every time the file changes is tedious or involves advanced build tooling. In contrast to putting the version number or a hash of the file itself into the name, it is common to put the file hash into the URL pointing to the file as a query string. E.g. /style.css?h=<sha256>. This way the file name can stay the same across changes to the file but the URL to the file changes.

Via the templating engine, the static site generator Zola provides a function get_url to generate the URL to a file containing a hash like the one above:

[...] you can also add a cachebust of the format ?h=<sha256> at the end of a URL by passing cachebust=true to the get_url function.

For example following HTML template

<link rel="stylesheet" href='{{ get_url(path="style.css", cachebust=true) }}' />

will be compiled by Zola to

<link rel="stylesheet" href='style.css?h=8a5403dd0e65034fa729' />

Which I find pretty neat. Regularly, I find myself delighted by the simplicity of both sourcehut services and Zola.

Published 2025-01-09 Last updated 2025-01-10