Hosting a Hugo site on GitHub's User Pages

This is the second half of my “Bootstrapping This Site” series. At the end of part one, we had hugo server generating a site for us on http://localhost:1313/ . In this second (shorter) article, I’ll discuss how to get that content pushed to a GitHub Pages user account with a custom domain. Happily, there are only a few steps and none of them are too difficult:

  1. Configure the custom domain’s DNS
  2. Add a CNAME file to the top-level of username.github.io
  3. Put the Hugo-generated public files on username.github.io

Configure the custom domain’s DNS

Github and David Singer both have good articles on DNS setup for GitHub Pages, but the action items are pretty simple: point my domain’s DNS records to GitHub’s servers, and set the CNAME record to $username.github.io. Namecheap is my registrar, and both of these things can be done through their Dashboard > Manage domain > Advanced DNS page:

Add a CNAME file

GitHub Pages needs to know about the custom domain. Its custom domain docs say this is done with a CNAME file in the toplevel, and Hugo’s docs say to add it to the static directory. This is straightforward:

# add CNAME
~/s/charlesk-hugo> echo "$yourdomain.com" > static/CNAME

# confirm it shows up in the toplevel
~/s/charlesk-hugo> hugo -t $yourtheme server
~/s/charlesk-hugo> wget -q localhost:1313/CNAME -O -
$yourdomain

# add it
~/s/charlesk-hugo> git add static/CNAME
~/s/charlesk-hugo> git commit -m "add CNAME for github pages custom domain"

Put the Hugo-generated public files on username.github.io

Since this is a User Pages site, rather than a project page, content must be served from username.github.io’s master branch. For this step, I used the suggestions in Hugo’s tutorials, so I have two repos:

  1. https://github.com/username/projectname-hugo holds my Hugo content (e.g. themes, markdown files, etc)

  2. https://github.com/username/username.github.io holds the files generated by hugo; e.g. my website

  3. make username.github.io a submodule in projectname-hugo/public, e.g.:

    $ cd projectname-hugo
    $ git submodule add -b master git@github.com:charlesk/charlesk.github.io.git public
  1. Now when content is generated into public/ by hugo, we can add-commit-push it to make the changes go live. A simple chmod +x deploy.sh script makes this easier:
#!/bin/bash

echo -e "\033[0;32mDeploying updates to GitHub...\033[0m"

# Build the project.
hugo # if using a theme, replace by `hugo -t <yourtheme>`

# Go To Public folder
cd public
# Add changes to git.
git add -A

# Commit changes.
msg="rebuilding site `date`"
if [ $# -eq 1 ]
  then msg="$1"
fi
git commit -m "$msg"

# Push source and build repos.
git push origin master

# Come Back
cd ..
  1. ./deploy.sh "Your optional commit message" to send changes to <username>.github.io (careful, you may also want to commit changes on the <your-project>-hugo repo).

That’s it! That’s how I generated the pages you’re reading now.

Share