這是一張有關標題為 Hugo Site Building Notes 的圖片

Hugo Site Building Notes

This is a site building note that details the step-by-step process of building a site using Hugo.

What is Hugo

According to the official website, Hugo is a fast and modern static site generator written in Go. The advantages of static web pages include performance and security, which are the main attractions.

With Hugo, Markdown content is encoded into HTML pages. Since the HTML pages are pre-built, users can load them with almost zero latency.

A key feature is that Hugo does not require backend programming or a database. This makes it more secure and less vulnerable compared to non-static web pages.

Dynamic Web Pages vs. Static Web Pages

Dynamic web pages refer to web pages whose content is dynamically generated or updated based on user requests, interactions, or other specific conditions at the time of access.

Server-side scripting is a key technology for implementing dynamic web pages. It enables the server to execute logic, generate corresponding content, and return the results to the user’s browser.

Common server-side scripting languages, ranked by popularity: Node.js, PHP, Ruby on Rails, Go, Python, ASP.NET, JSP, CGI, etc.

In the past, I have used WordPress, a content management system (CMS), when writing blogs. WordPress is developed in PHP and requires a host machine to set up, which can run on either Windows or Linux systems. The host can be deployed on cloud services or local environments, typically provided by hosting service providers. After setup, an FTP or SSH configuration provided by the host must be used to connect. On the host, Apache or Nginx must be installed to handle HTTP requests, as well as PHP to run WordPress. Additionally, MySQL or MariaDB databases are required to store content. For convenient database management, graphical tools like phpMyAdmin can be installed (optional).

Once WordPress is installed and running, several configurations are typically performed, such as basic settings, SEO optimization, theme customization, and plugin installation. Currently, most travel blogs in Taiwan still widely use this system. When end users browse articles, the basic operation process for dynamic web pages is as follows:

The user sends an HTTP Request via the browser → Apache processes the request and forwards it to PHP → PHP queries the database and generates HTML → Apache returns the HTML as an HTTP Response to the user.

In contrast, static web pages only require Apache to handle user requests and responses. There is no need to rely on PHP or other server-side scripts to dynamically generate content. Static web pages are fast, secure, and capable of presenting content to users instantly without waiting for server-side programs to complete execution. The basic operation process for static web pages is as follows:

The user sends an HTTP Request → Apache serves static HTML → Apache returns the HTTP Response to the user.

The key difference between the two lies in whether the server needs to execute server-side scripts to generate content while the user is browsing. Static web pages do not require server-side program execution or database access to retrieve articles. Most content is pre-generated as single HTML files during deployment and served directly to users, making static web pages faster and simpler.

Website Building Process

Below is the basic process for building a website. You can refer to the diagram for the structure and follow the steps in order. Each step will be explained in detail later, and more in-depth content will be supplemented in future articles if needed:

  1. Start and Install
    Install the necessary tools (e.g., Hugo and Git).

  2. Start a New Website
    Create a new website project using Hugo.

  3. Initialize Git Repo
    Initialize the project as a Git repository for version control.

  4. Install a Hugo Theme
    Choose and install an appropriate Hugo theme to enhance the website’s appearance.

  5. Create New Content
    Add new content, such as blog posts or pages.

  6. Configure Website Details
    Adjust the website’s configuration file (e.g., config.toml), including the site title, description, and other parameters.

  7. Run Hugo Server
    Start the Hugo development server locally to preview the website.

  8. Push to Remote Repository
    Use Git to push the website project to a remote repository (e.g., GitHub).

  9. Build and Deploy the Website
    Use Hugo to compile the website into static files and deploy it to a hosting service or CDN.

Flow chart to build Hugo sites

Flow chart to build Hugo sites

Getting Started and Installation

Installing Hugo on Windows and Linux is very simple and quick. It is recommended to use the command line for installation to ensure faster and more consistent operations.

In addition to installing Hugo, Windows users will also need to install Git for version control of source files.

When editing articles in the future, if any errors occur and need to be reverted, Git can be used to quickly restore previous versions.

Install Hugo via Winget (Windows)

1
winget install Hugo.Hugo.Extended

Result:

Use winget to install Hugo

Install Hugo via Snap (Linux)

1
sudo snap install hugo

Result:

wells@server:~$ sudo snap install hugo

[sudo] password for wells:

hugo 0.120.4 from Hugo Authors installed

Install Hugo via Homebrew (macOS, Linux)

Before using brew, install Homebrew

1
brew install hugo

Install Git via Winget (Windows)

Assuming Git is pre-installed on Linux or Mac, here is the Windows installation:

1
winget install -e --id Git.Git

Use winget to install Git

Check Executable Versions

Verify successful installation and check versions. Currently installed versions are Hugo v0.120.4 and Git v2.43.0

1
2
3
4
5
wells@server:~/wellwells_hugo$ hugo version
hugo v0.120.4-f11bca5fec2ebb3a02727fb2a5cfb08da96fd9df+extended linux/amd64 BuildDate=2023-11-08T11:18:07Z VendorInfo=snap:0.120.4

wells@server:~/wellwells_hugo$ git --version
git version 2.43.0

Start a New Site

In a directory where you want to store your blog source files, choose your Home directory (~/) on Linux or the User directory (C:\Users\USER) on Windows. You can also choose other locations as desired. To start a new site, enter hugo new site BLOG_NAME and navigate into the directory. Here is an example using my_blog:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
wells@server:~$ hugo new site my_blog
Congratulations! Your new Hugo site was created in /home/wells/my_blog.

Just a few more steps...

1. Change the current directory to /home/wells/my_blog.
2. Create or install a theme:
   - Create a new theme with the command "hugo new theme <THEMENAME>"
   - Install a theme from https://themes.gohugo.io/
3. Edit hugo.toml, setting the "theme" property to the theme name.
4. Create new content with the command "hugo new content <SECTIONNAME>/<FILENAME>.<FORMAT>".
5. Start the embedded web server with the command "hugo server --buildDrafts".

See documentation at https://gohugo.io/.

wells@server:~$ cd my_blog/
wells@server:~/my_blog$ ls # List directory structure
archetypes  assets  content  data  hugo.toml  i18n  layouts  static  themes

A new blog site is created, which by default has no theme or content. Direct compilation will result in an empty site.

Initialize Git Repo

Navigate to the blog directory (~/my_blog) and initialize a local Git repo with git init. Use git status to check Untracked files.

By default, Git does not track any files. Add hugo.toml, archetypes, and other relevant files to the index (git add).

 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
36
37
38
39
wells@server:~/my_blog$ git init
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint: 
hint:   git config --global init.defaultBranch <name>
hint: 
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint: 
hint:   git branch -m <name>
Initialized empty Git repository in /home/wells/my_blog/.git/
wells@server:~/my_blog$ git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .hugo_build.lock
        archetypes/
        hugo.toml

nothing added to commit but untracked files present (use "git add" to track)

wells@server:~/my_blog$ git add archetypes/ hugo.toml
wells@server:~/my_blog$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file:   archetypes/default.md
        new file:   hugo.toml

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .hugo_build.lock

Install Hugo Theme

To install a Hugo theme, visit Hugo Themes and choose a theme. Theme providers usually provide installation instructions.

Using PaperMod as an example, follow the PaperMod - Installation guide. Method 1 involves git cloning in the site directory.

1
2
3
4
5
6
7
8
wells@server:~/my_blog$ git clone https://github.com/adityatelange/hugo-PaperMod themes/PaperMod --depth=1
Cloning into 'themes/PaperMod'...
remote: Enumerating objects: 134, done.
remote: Counting objects: 100% (134/134), done.
remote: Compressing objects: 100% (113/113), done.
remote: Total 134 (delta 33), reused 57 (delta 15), pack-reused 0
Receiving objects: 100% (134/134), 263.32 KiB | 1.61 MiB/s, done.
Resolving deltas: 100% (33/33), done.

Edit ~/my_blog/hugo.toml and add the following line at the end to apply the theme. Note that the case is important:

1
2
3
4
baseURL = 'https://example.org/'
languageCode = 'en-us'
title = 'My New Hugo Site'
theme = 'PaperMod'

Start a New Article

With the following command, you can create a new article:

1
2
wells@server:~/my_blog$ hugo new content posts/my-first-post.md
Content "/home/wells/my_blog/content/posts/my-first-post.md" created

Editing ~/my_blog/content/posts/my-first-post.md is equivalent to writing an article. The syntax used is Markdown. Remember to change draft = true to draft = false to ensure that the article is in the release state.

my-first-post.md

1
2
3
4
5
6
7
8
+++
title = 'My First Post'
date = 2023-11-27T10:58:32+08:00
draft = false
+++

Hello, My Site
I'm Wells

Website Configuration

At this stage, the Hugo server can already be run, and the blog can be viewed. However, before running the server, you may consider configuring some basic settings for the website, such as:

  1. Editing the language in ~/my_blog/hugo.toml.
  2. Setting the blog name.
  3. Enabling or disabling emoji support (enableEmoji).
  4. Configuring the website’s favicon.
  5. Adding a website summary.
  6. Other configuration options…

Since there are numerous configuration options, you can also choose to adjust them dynamically after running the server.

For more configuration details, refer to the official documentation: Configure Hugo. Additionally, you can convert hugo.toml to hugo.yaml based on your preferences.

Different Hugo themes may require specific configurations. It is recommended to consult the theme’s documentation and adjust the corresponding settings in the config file accordingly.

Running the Hugo Server

According to the official website, Hugo is a high-performance web server, though it is mainly convenient for local testing. You can run the server with the following command:

1
hugo server -D

Including the -D flag will also build draft articles. By default, the final build will not compile draft articles.

 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
wells@server:~/my_blog$ hugo server -D
port 1313 already in use, attempting to use an available port
Watching for changes in /home/wells/my_blog/{archetypes,assets,content,data,i18n,layouts,static,themes}
Watching for config changes in /home/wells/my_blog/hugo.yaml
Start building sites … 
hugo v0.120.4-f11bca5fec2ebb3a02727fb2a5cfb08da96fd9df+extended linux/amd64 BuildDate=2023-11-08T11:18:07Z VendorInfo=snap:0.120.4


                   | ZH-TW  
-------------------+--------
  Pages            |    10  
  Paginator pages  |     0  
  Non-page files   |     0  
  Static files     |     0  
  Processed images |     0  
  Aliases          |     2  
  Sitemaps         |     1  
  Cleaned          |     0  

Built in 25 ms
Environment: "development"
Serving pages from memory
Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender
Web Server is available at http://localhost:46651/ (bind address 127.0.0.1) 
Press Ctrl+C to stop

After starting the server, you can open http://localhost:46651 in your browser to view the blog and articles. Any subsequent edits to the configuration or modifications to the articles will be updated in real-time.

Running the Hugo Server

Pushing to a Remote Server

After installing the theme, adding articles, and editing the configuration files, the next step is to use Git to manage the changes in the directory and push these changes to a remote server for management and maintenance.

Since only git init was executed earlier, the remote server connection has not been configured yet.

Assuming you have already created a corresponding repository (repo) on GitHub or another server, you will receive an SSH connection string, such as:

1
git@github.com:USER/private.repo.git

You can add and check the current local repository’s remote status using git remote add and git remote -v:

1
2
3
4
wells@server:~/my_blog$ git remote add main git@github.com:USER/private.repo.git
wells@server:~/my_blog$ git remote -v
main    git@github.com:USER/private.repo.git (fetch)
main    git@github.com:USER/private.repo.git (push)

Ensure that all modified files have been added to the index using git add, and that the changes are committed using git commit. Once this is done, you can push the local changes to the remote server using git push.

Building and Publishing the Website

Building the website is straightforward. Simply enter the command hugo, and it will generate the ~/my_blog/public directory. The HTML files within this public directory can be uploaded to a server for others to view. There are several free static site hosting services available online, such as:

  1. GitHub pages
  2. Cloudflare pages
  3. Netlify

Among these, we are currently using GitHub Pages, which supports custom domains and integrates with repositories and GitHub Actions.

This setup allows for automatic building and pushing to GitHub Pages after each repository push. The free monthly quota is quite sufficient for most users.

Conclusion

Creating a Hugo static website is not particularly difficult. The steps are straightforward: install Hugo and Git → install a theme → add articles → publish.

Introducing Git into the process ensures that you can track and revert changes made to the website. While it’s technically possible to skip git init, it is highly discouraged. Reverting changes manually can be quite challenging if the website gets accidentally broken.

References

  1. Hugo - Quick start
  2. Benefits of static site generators
  3. Configure Hugo
  4. Hugo Themes
  5. PaperMod’s wiki
Theme Stack designed by Jimmy