Short URLs for Zola on Cloudflare Pages
This website is implemented in Zola and deployed with Cloudflare Pages.
Recently I came across Cloudflare's Redirects configuration (deriving, I think, from the Netlify original?) and it occured to me that I could combine it with Zola's feed templates. The result is a pretty satisfying hack for auto-generating shortened URLs for every post.
Hashing a post's slug generates a reproducible value, and encoding with base64 ensures just four characters (probably) enough to avoid collisions into the thousands of posts. That's more than enough for any blogging cadence that I'll realistically achieve, and I'd probably hit Cloudflare's 2,000 static redirect limit first in any case. Zola's base64 uses a URL-unfriendly '/' as one of the characters, so I simply replace that with a friendlier '-'.
Implementing this template:
{%- for page in pages %}
/{{ get_hash(literal=page.slug, sha_type=256, base64=true) | replace(from='/', to='-') | truncate(length=4, end="") }} {{ page.permalink | safe }} 301
{%- endfor %}
... and adding it to feed_filenames
in Zola's config.toml
, generates the following output:
/mfIw https://denis.milanovic.au/posts/zola-shortener/ 301
/r6J7 https://denis.milanovic.au/posts/hello-world/ 301
So far so good, but things start getting ugly when trying to output to the /_redirects
path.
Zola requries that its templates' file suffixes be .md
or end in "ml" (as in .xml
, .html
, but also .foobarml
), and feed templates - designed with atom.xml
in mind - output the same filename as the input.
So far, I haven't found a better solution than modifying the build step on Cloudflare to explicitly rename this file - i.e. zola build && mv public/redirects.md public/_redirects
. If there's a cleaner way of doing this, ideally on the Zola side, please let me know.
So now I have 17 characters - milanovic.au/mfIw - instead of 39 characters - denis.milanovic.au/posts/zola-shortener, which is 22 more characters of rage I can fit into a tweet/toot/skeet. Or more, if I can get myself a shorter domain.
[2024-12-30 Update] Using base64 instead of hexadecimal hash output allows an even shorter domain, now reflected above.