HUGO

.htaccess, humans.txt with template logic

How to have Hugo generate .htaccess, humans.txt, and other similar files while being able to use template logic and site variables.

Option 1: Outputs

We define custom output formats.

// config.toml
[outputs]
home = ["HTML", "htaccess", "humanstxt"]

[outputFormats]
[outputFormats.htaccess]
    baseName = ""
    isPlainText = true
    mediaType = "text/htaccess"

[outputFormats.humanstxt]
    baseName = "humans"
    isPlainText = true
    mediaType = "text/plain"

And a custom mediaType in the case of .htaccess:

// config.toml
[mediaTypes]
  [mediaTypes."text/htaccess"]
    suffixes = ["htaccess"]

Then we define layouts.

// layouts/index.humanstxt.txt
// layouts/index.htaccess
{{ site.BaseURL }}

These generate:

// public/humans.txt
// public/.htaccess
https://example.com/

Option 2: Assets*

**** This only works if you will be invoking the .Permalink for the generated file. ****

// assets/txt/alsohumans.txt
{{ site.BaseURL }}
<!-- somewhere in your baseof/head -->
{{ $alsohumans := resources.Get "txt/alsohumans.txt" | resources.ExecuteAsTemplate "alsohumans.txt" . }}
<link type="text/plain" rel="author" href="{{$alsohumans.Permalink}}" />

This generates:

// public/alsohumans.txt
https://example.com/

These work as of time of posting.

Hugo Static Site Generator v0.74.3-DA0437B4/extended linux/amd64 BuildDate: 2020-07-23T16:30:30Z

5 Likes

Great work. i was looking for a good description on how to create customer output formats.

I use this to create the htaccess content (I needed it when I migrated Wordpress to Hugo):

{{ range .Site.Pages }}
{{ if .Aliases }}
{{ $new := .RelPermalink }}
{{ range .Page.Aliases }}
<p>Redirect 301 {{ . }} {{ $new }}</p>
{{ end }}
{{ end }}
{{ end }}
2 Likes