Featured image of post Setting up a SSG on NixOs with nginx

Setting up a SSG on NixOs with nginx

Using hugo we can compile a project into a static site which can be later served with Nginx

# Overview

After conducting research and finding insufficient guidance online on how to properly set up a Hugo site with nginx, I decided to create my own guide. I will provide you with step-by-step instructions on how to compile your Hugo project into a static site, which can then be served through nginx’s root option.

# Defining the derivation to build the site

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# /website/default.nix
{ pkgs }:

pkgs.stdenv.mkDerivation rec {
  name = "website";
  version = "0.1.0";
  src = /home/user/website;

  buildInputs = with pkgs; [ hugo ];
  dontConfigure = true;

  buildPhase = ''
    cp -r $src/* .
    ${pkgs.hugo}/bin/hugo
  '';

  installPhase = ''
    mkdir -p $out
    cp -r public/* $out/
  '';
}

# Setting up Nginx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# /services/nginx.nix
{...}: {
  services.nginx = {
    enable = true;
    virtualHosts = {
      "example.com" = {
        forceSSL = true;
        enableACME = true;

        locations."/" = {
          # Relative path to current file
          root = pkgs.callPackage ../website/default.nix { };
        };
        # setting error page as hugo error page
        extraConfig = ''
          error_page 404 /404.html;
        '';
      };
    };
  };
  }

# Rebuild the system

After importing this module to your flake.nix/configuration.nix you can rebuild the system and see that the site is up!

1
sudo nixos-rebuild switch
Licensed under CC-BY-SA 4.0
Last updated on Apr 24, 2024 00:00 UTC