Caching and Redirecting with Cloudflare Pages and Hugo
A websites performance can be improved drastically by creating a _redirects and a _headers file. This means improving asset caching and improved alias handling in Hugo.
_headers
The syntax for _headers is:
[url]
[name]: [value]
Instead of writing down all urls, wildcards (*) can be used:
|
|
Cloudflare Pages does not cache Javascript or CSS on its own. I fell into that trap at first, but using _headers, it was quite easy to fix the problem.
To create the file automatically with the rest of your page, it can be saved to the static Folder in Hugo. It will get automatically copied to the output directory.
_redirects
The redirects created with Hugo are somewhat difficult for SEO, since they do redirect the users, but also contain a noindex-tag. The tag is necessary since the page would still show up in search results, but Cloudflare Pages contains functionality to create SEO-friendlier 301-redirects.
The syntax for _redirects is:
/source /target 3xx
To create this file automatically, you just add the following to hugo.toml:
|
|
and themes/your-theme/layouts/index.redir in your theme as follows:
|
|
The configuration in hugo.toml deactivates the creation of HTML-redirects and produces a _redirects file with the contents of index.redir.
index.redir iterates over all pages and creates a redirect (with and without terminating /) for all aliases with the status code 301. Cloudflare Pages allows codes 301, 302, 303, 307 and 308, with the default being 302.
Uploading this file creates redirects automatically.
Conclusion
If a website is hostet on Cloudflare Pages anyway, these two tweaks help improve the sites performance drastically.