Deutsch

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:

1
2
3
4
5
6
7
# cache fingerprinted CSS
/assets/*.css
  Cache-Control: max-age=31536000

# Always use HTTPS
/*
  strict-transport-security: max-age=31536000

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
disableAliases = true

[outputs]
  home = ['html', 'rss', 'redir']

[mediaTypes]
  [mediaTypes."text/cf-redir"]
    suffix = ""
    delimiter = ""

[outputFormats.REDIR]
  baseName = "_redirects"
  isPlainText = true
  mediaType = "text/cf-redir"
  notAlternative = true

and themes/your-theme/layouts/index.redir in your theme as follows:

1
2
3
4
5
6
7
{{- $index := slice -}}
{{- range $p := .Site.Pages -}}
{{- range .Aliases -}}
{{ if hasSuffix . "/" }}{{ strings.TrimRight "/" . }} {{ $p.RelPermalink }} 301{{ end }}
{{ . }} {{ $p.RelPermalink }} 301
{{ end -}}
{{- end -}}

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.