How to deploy hugo static on specific environments

Problem

How to deploy my static web site to different environments without changing all the time the configuration. The full url is used to generate the static pages, making it difficult to deploy on the fly from dev to prod without updating the config. When I m developping on my laptop, I am using localhost, but once I m committing my changes, my static website is compiled by Netlify and deployed automatically. So I have to remind myself not to forget to update the toml file before committing.

But there is an easy way to fix this.

Split Config Files

Since version 0.110 we can use hugo.toml and we can use a structure to define different configuration for different configuration. In the config folder, we have _default we the complete config. This config is used for my dev, it will be picked up by my hugo-serve -D command.

In the homeserver and netlify folders the hugo.toml files only contain the baseURL entries that are different from the default values. All the other entries are automatically taken back from the _default folder.

1
2
3
4
5
6
7
8
9
├── config
   ├── _default
      ├── hugo.toml
      └── languages.toml
   ├── homeserver
      └── hugo.toml
   └── netlify
       ├── hugo.toml
       └── netlify.toml

Use Netlify.toml

In the netlify.toml file I am just updating the build command to contain the environment corresponding to my netlify deployment.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[build]
publish = "public"
command = "hugo --gc --minify --environment netlify"

[context.production.environment]
HUGO_VERSION = "0.114.1"
HUGO_ENV = "production"
HUGO_ENABLEGITINFO = "true"

[context.split1]
command = "hugo --gc --minify --enableGitInfo"

[context.split1.environment]
HUGO_VERSION = "0.110.1"
HUGO_ENV = "production"

[context.deploy-preview]
command = "hugo --gc --minify --buildFuture -b $DEPLOY_PRIME_URL"

[context.deploy-preview.environment]
HUGO_VERSION = "0.114.1"

[context.branch-deploy]
command = "hugo --gc --minify -b $DEPLOY_PRIME_URL"

[context.branch-deploy.environment]
HUGO_VERSION = "0.99.1"

[context.next.environment]
HUGO_ENABLEGITINFO = "true"

[[redirects]]
from = "/npmjs/*"
to = "/npmjs/"
status = 200