Hugo 静态网站部署

I. 前提条件

1.1 安装 Hugo

1.1.1 Windows

  1. 下载 Hugo(建议下载扩展版): Hugo(github.com)

  2. 解压 Hugo 压缩包到指定目录。

  3. 【Win + R】打开运行框,输入以下命令:

1
sysdm.cpl

打开”系统属性“对话框,依次点击 “高级” -> 环境变量 -> 系统变量,在 Path 变量中点新建,添加 Hugo 解压目录如:

1
D:\Portable\Hugo

1.1.2 MacOS

1
brew install hugo

1.1.3 Linux

官方文档: Linux | Hugo (gohugo.io)

1.1.4 确认安装

在终端/命令行窗口,输入以下命令:

1
hugo version

如果有正常显示你所选择安装的 Hugo 版本,则表示安装正确。

1.2 安装 Git

Git - Installing Git (git-scm.com)

II. 创建站点

2.1 安装确认

确认已安装 Hugo v0.112.0 或更高版本,在 Git Bash 下执行以下命令:

1
hugo version

2.2 创建站点

  1. 在本地选择合适的站点存放路径。
  2. 在 Git Bash 中执行以下命令为站点创建 目录结构
1
hugo new site blog

2.3 创建源码仓库

  1. 登录 GitHub 仪表板。
  2. 创建仓库并命名,如:blog
  3. ⨀ Private(设置为私有仓库)

2.4 关联源码仓库

1
2
3
4
5
6
7
8
cd blog
git init -b main
git remote add origin git@github.com:user/repo.git
git pull --rebase origin main
git add .
git commit -m "Initial commit"
git branch -M main
git push -u origin main

2.5 指定不跟踪文件

在站点根目录新建 .gitignore 文件,添加内容:

1
2
# 屏蔽运行产生文件
.hugo_build.lock

III. 主题配置

3.1 主题下载

可从 Hugo Themes 官方,或根据 awesome-hugo-themes 的 GitHub Stars 数量排行下载自己喜欢的主题,本教程使用 Hugo NexT 主题 v4.7.2 版,“双子座 (Gemini)” 页面布局(默认)。

1
2
3
4
5
6
cd blog
mv hugo.toml hugo.toml.bak
git submodule add https://github.com/hugo-next/hugo-theme-next.git themes/hugo-theme-next
cp themes/hugo-theme-next/exampleSite/hugo.yaml .
mv hugo.toml hugo.toml.bak
git submodule update --init --recursive

💡提示:
下载 github 子模块你可能需要配置代理(请替换实际 <port>
git config --global http.https://github.com.proxy socks5://127.0.0.1:<port>
取消代理:
git config --global --unset http.https://github.com.proxy

让 Git 在执行 git clonegit pull 时自动更新子模块:

1
git config submodule.recurse true

查看主题版本

1
2
cd themes/hugo-theme-next/
git describe --tags

📓 切换到开发版:

  1. 进入主题目录:cd themes/hugo-theme-next/
  2. 切换到开发分支:git checkout develop
  3. 拉取最新代码:git pull origin develop
  4. 回到项目根目录,查看效果:hugo server -D

3.2 主题预览

📢 注意:
本教程使用的是 Hugo NexT 主题,版本 v4.7.2 ,不同版本配置可能有差异,仅供参考。

  1. 添加自定义文件
1
2
3
4
mkdir layouts/partials
cp themes/hugo-theme-next/exampleSite/layouts/partials/* layouts/partials/
mkdir static/css
cp themes/hugo-theme-next/exampleSite/static/css/* static/css/
  1. 复制示例文章及目录以供后续预览展示
1
cp -r themes/hugo-theme-next/exampleSite/content/* content/
  1. 在主题配置过程中,你可以随时在 Git Bash 中输入以下命令:
1
hugo server -D

在浏览器中打开 localhost:1313 查看主题本地展示效果(若此链接打不开,可在 Bash 命令输出中查看实际链接)。

3.3 站点信息

编辑 blog/hugo.yaml 站点配置文件,请根据实际修改

 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
# 站点域名,比如: https://hugo-next.eu.org
# Website domain, eg: https://hugo-next.eu.org
baseURL: www.example.com
# 站点标题
# Website title
title: 小明的博客

.....
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......
  
  # 站点基本信息
  # Site Information Settings
  author: 小明
  subtitle: 一个有趣的博客小站
  description: 在这里记录我的喜怒哀乐。
  keywords: IT,前端,Web

  # 不同尺寸站点图标
  # Different size of favicon
  favicon:
    icon: /imgs/icons/favicon.ico
    small: /imgs/icons/favicon-16x16.png
    medium: /imgs/icons/favicon-32x32.png
    appleTouchIcon: /imgs/icons/apple-touch-icon.png

📌 配置说明:
blog/static/imgs/icons/ 目录上传自定义站点图标( Discussion #38 )。

3.4 自定义菜单

  1. 示例菜单一般都需要重新配置,以下配置项按实际增减
 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
menus:
  main:
    - identifier: home
      name: 首页
      pageRef: /
      pre: home
      weight: 1
    - identifier: tech
      name: 技术
      pageRef: /tech
      pre: screwdriver-wrench
      weight: 2
    - identifier: live
      name: 生活
      pageRef: /live
      pre: umbrella-beach
      weight: 3
    - identifier: about
      name: 关于
      pageRef: /about
      pre: user
      weight: 4
    - identifier: flinks
      name: 友链
      pageRef: /flinks
      pre: thumbs-up
      weight: 5
    - identifier: commonweal
      name: 公益
      pageRef: /404.html
      pre: heartbeat
      weight: 6

💡 Tips:
更换菜单后可能同时需要更换菜单图标,打开 Font Awesome 网站 Icons 菜单,搜索你定义的菜单名称或相近名称(英文)。如这里为“技术”菜单找到了相近图标,点击图标从 “VUE” 菜单下 “Default Style” 选项卡中提取如下参数 screwdriver-wrenchDiscussion #88 ),然后在上面"技术"菜单下更新参数 pre: screwdriver-wrench

1
<font-awesome-icon icon="screwdriver-wrench" />
  1. 增删菜单项后,还需配置相应目录以在主页展示文章( Discussion #98 )👇
1
2
3
4
5
6
params:
  # 需要显示文章的部分,即content目录下的文件夹名称
  # Sections for show in home & archive page 
  # and it's forlder name which under content
  mainSections: ["tech", "live"]
  ......
  1. 还需创建实际文章存放目录( Discussion #47
1
mkdir content/{tech,live}

💡 Tips:
为了查看实际展示效果,可把示例文章复制到上面创建的文章目录。

3.5 多语言(可选)

如果你的站点不需要展示多语言,可在主题配置文件 hugo.yaml 中,注释或删除以下配置👇

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
languages:
  zh-cn:
    languageCode: zh-CN
    languageDirection: ltr
    languageName: "简体中文"
    weight: 1    
  en-us:
    languageCode: en-US
    languageDirection: ltr
    languageName: English
    weight: 2
    menus:
      main:
        - identifier: home
          name: Home
          pageRef: /
          pre: home
          weight: 1
        - identifier: about
          name: About
          pageRef: /about.html
          pre: user
          weight: 2
        - identifier: flinks
          name: Friend's Links
          pageRef: /flinks.html
          pre: thumbs-up
          weight: 3
        - identifier: example
          name: Example
          pre: angles-down
          weight: 4
        - identifier: syntax
          name: Syntax Highlighting
          pageRef: /post/09-syntax-highlighting
          weight: 1   
          parent: example
        - identifier: math
          name: Math Formula
          pageRef: /post/10-math-formula
          weight: 2   
          parent: example
          parent: example
        - identifier: flow-charts
          name: Flow Charts
          pageRef: /post/11-mermaid-charts
          weight: 3
          parent: example
        - identifier: archives
          name: Archives
          pageRef: /archives
          pre: archive
          weight: 5
        - identifier: commonweal
          name: Commonweal404
          pageRef: /404.html
          pre: heartbeat
          weight: 6
    params:
      yearFormat: "2006"
      monthFormat: "01/02"
      dateFormat: "2006/01/02"
      timeFormat: "2006/01/02 15:04:05 -07:00"

      author: NexT Theme
      subtitle: Build for Hugo Theme
      description: Keep it simple, keep it powerful.
      keywords: Hugo,NexT,theme,simple,powerful

      linksSets:
        title: Links
      
      footer:
        beian:
          enable: false
      
      postFooter:
        endLineTip: "~ End Line ~"
      
      rewardSets:
        comment: '<i class="fa-solid fa-mug-hot"></i>  How about you buy me a coffee?ヾ(^▽^*)))'

3.6 侧边栏

3.6.1 头像更换

把准备好的头像存放到指定目录,修改头像路径,如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # 侧边栏头像
  # Sidebar Avatar
  avatar:
    # 设置显示头像的相对路径
    # Replace the default image and set the url here.
    url: /imgs/icons/avatar.png

3.6.2 日志重命名(可选)

把侧边栏的“日志”改为“文章”

1
cp themes/hugo-theme-next/i18n/zh-cn.yaml i18n/

i18n/zh-cn.yaml 中的“日志”改为“文章”

1
2
3
4
5
6
7
8
Sidebar:
  label:
    posts: 文章
    ......

Terms:
  archives: "目前共计 <strong>{{ .Count }}</strong> 篇文章"
  ......

3.7 站点统计(可选)

  1. 注册 51la 账号

  2. 修改站点配置

 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
40
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  siteState: 
    # 是否在侧边栏显示文章、分类、标签信息
    # Posts / Categories / Tags in sidebar.
    basic: true
    # 站点访问信息
    # Site's view information
    views:  
      enable: true
      # 组件类型,可选值为: 51la, busuanzi
      # 使用51la时需要注册账号:https://invite.51.la/
      # Plguin value is: 51la, busuanzi
      plugin: 51la
  ......
  
  analytics:
    # 51La 站点统计
    # 更多信息请参考:https://invite.51.la/1NUfGTS1?target=V6
    # 51La Analytics
    # See: https://invite.51.la/1NUfGTS1?target=V6 
    #laId: #<anaytics_id> 
    laId: 123456789ABCDEFG
    # 百度统计
    # Baidu Analytics
    #baidu: #<anaytics_id>
    # 谷歌统计
    # Google Analytics
    #google: #<anaytics_id>
    # 不蒜子统计
    # Show Views / Visitors of the website / page with busuanzi.
    # For more information: http://ibruce.info/2015/04/04/busuanzi/
    #busuanzi:
    #  visitorsIcon: fa fa-user
    #  viewsIcon: fa fa-eye

3.8 文章展示(可选)

3.8.1 标题边框

去掉文章正文中 3 级和 4 级标题下方横线。在站点配置文件中开启“用户自定义文件配置”,如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......
  
# 用户自定义文件配置
# Define custom file paths.
  customFilePath:
    sidebar: custom_sidebar.html
    footer: custom_footer.html
    style: /css/custom_style.css

static/css/custom_style.css 添加以下内容

1
2
3
4
5
6
7
.post-body h1,.post-body h2 {
    border-bottom: 1px solid #eee
}

.post-body h3,.post-body h4 {
    border-bottom: 0px dotted #eee
}

3.8.2 数学公式渲染

数学公式不建议全局开启,以减少不必要的资源加载消耗。可在文章元数据中开启数学公式支持。

1
2
3
4
5
---
math: katex 
<!-- 或 -->
math: mathjax
---

3.9 其它配置(可选)

3.9.1 友情链接

根据需求修改或删除:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # 友情链接地址
  # 用法: `Key: 显示名称 || 链接地址`
  # Links of your friends
  # Usage: `Key: name || permalink`
  links: 
    link0: Hugo-NexT || https://gitee.com/hugo-next/hugo-theme-next
    link1: 凡梦星尘空间站 || https://lisenhui.cn

💡 Tips:
侧边栏“支持自定义CSS和Sidebar布局啦”及网页底部“Website source code”文字,可在用户自定义文件中删除。

3.9.2 标题序号

在当前主题下,文章标题会自动设置列表数字。如果文章标题有自定义序号,会重复显示。这里设置不自动添加列表数字(按需修改):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......
  
  # 文章目录显示
  # Table of Contents in the Sidebar
  # Front-matter variable (nonsupport wrap expand_all).
  toc:
    enable: true
    # 自动设置列表的数字
    # Automatically add list number to toc.
    number: false

3.9.3 社交链接

按需修改:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  socials: 
    social0: Github || https://github.com/elkan1788 || fab fa-github
    #social1: E-Mail || mailto:yourname@gmail.com || fa fa-envelope
    social2: 知乎 || https://www.zhihu.com/people/lisenhui || fa fa-book
    #Google: https://plus.google.com/yourname || fab fa-google
    ......

3.9.4 备案和供应商

按需修改:

 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
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # ---------------------------------------------------------------
  # 站点底部设置
  # Footer Settings
  # ---------------------------------------------------------------
  footer:    
    ......

    # 国内 ICP 备案和公安网备信息
    # Beian ICP and gongan information for Chinese users. 
    # See: https://beian.miit.gov.cn, http://www.beian.gov.cn
    beian:
      enable: false
      ......

    # 站点支持供应商列表
    # Vendors list who support website. 
    vendors:
      enable: false
      ......

3.9.5 捐赠

按需修改:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # 捐赠信息设置
  # Donate (Sponsor) settings.
  rewardSets:
    # 是否开启捐赠按钮,开启后将在每个文章页面底部显示
    # If true, a donate button will be displayed 
    # in every article by default.
    enable: false
    ......

3.9.6 订阅

按需修改:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # 提供其它订阅站点文章的方式
  # 用例: `key: 名称 || 链接(图像地址)|| icon名称`
  # Subscribe through Telegram Channel, Twitter, etc.
  # Usage: `Key: name || permalink || icon` (Font Awesome)
  followMe:
    #channel0: Twitter || https://twitter.com/username || fab fa-twitter
    #channel1: Telegram || https://t.me/channel_name || fab fa-telegram
    channel2: WeChat || /images/wechat_channel.jpg || fab fa-weixin
    channel3: RSS || /atom.xml || fa fa-rss

3.9.7 在线编辑

按需修改:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # 文章的在线编辑
  # Post edit
  # Easily browse and edit blog source code online.
  postEdit:
    enable: false
    url: https://github.com/user-name/repo-name/tree/branch-name/subdirectory-name/

3.9.8 GitHub 关注

按需修改:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # 右上角在 Github 上面关注我的横幅
  # `Follow me on GitHub` banner in the top-right corner.
  githubBanner:
    # 是否开启显示
    # If true, will display banner.
    enable: false
    ......

3.9.9 评论组件

按需修改:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # 评论组件设置,最多支持2个显示
  # Multiple Comment System Support
  comments:
    # 开启评论组件
    # If true, will show comment component in post end.
    enable: false   
    ......

📓 文章浏览/评论显示:
若指定了评论组件,需在"开启文章头部元素显示"中指定相应插件。如 waline3 插件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#-----------------------------------------
# Hugo NexT 主题参数配置
# Configure Settings for Hugo NexT theme
#-----------------------------------------
params:
  ......

  # 开启文章头部元素显示
  # Post meta display settings
  postMeta:
    ......

    # 是否开启评论数显示
    comments: 
      enable: true
      # 评论统计插件,暂只支持waline和waline3
      # Comment counter plugin, only support waline and waline3
      plugin: waline3
    # 是否开启页面访问数显示
    views:
      enable: true
      # 页面访问统计插件,支持busuanzi, waline, waline3
      # Page views counter plugin, support: busuanzi, waline, waline3
      plugin: waline3

IV. 创建文章

4.1 配置文章模板

修改 blog\archetypes\default.md 中的参数,把 draft = true (表示这是一个草稿) 修改为 draft = false ,这样生成的文章默认就是可以发表的。

4.2 发布文章

4.2.1 创建文章

1
hugo new posts/knowledge/hello-world.md

4.2.2 增加前置格式

使用 Front matter 为 Hugo 文章添加元数据。以下为示例配置:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
---
title: Hugo 静态网站部署
slug: hugo-static-website-deployment
url: /tech/hugo-static-website-deployment
categories: 
  - Blog
tags:
  - Hugo
  - NexT
draft: false
date: 2024-06-21T17:17:00+08:00
lastmod: 2025-01-12T13:07:00+08:00
---

📌 参数说明:

  • slug : (字符串) 覆盖 URL 路径的最后一段。不适用于章节页面。详情请参阅 URL 管理页面 。使用页面对象上的 Slug 方法从模板访问此值。
  • url : (字符串) 覆盖整个 URL 路径。适用于常规页面和部分页面。详情请参阅 URL 管理页面

4.3 生成网页

通过以下命令在本地实时预览当前编辑内容:

1
hugo server -D

通过终端中显示的 URL 查看博客。按 **Ctrl + C ** 停止 Hugo 的开发服务器。

4.4 发布内容

hugo 命令可以将你写的 Markdown 文件生成静态 HTML 网页,生成的 HTML 文件默认存放在站点路径下的 public 目录中。

1
hugo

V. 自动部署

5.1 GitHub Page 部署

5.1.1 创建 GitHub Pages

  1. 登录 GitHub 仪表板。
  2. 创建仓库并命名:<username>.github.io (username 必须是当前登录 GitHub 用户名)。
  3. ⨀ Public(设置为公开仓库)。

5.1.2 生成 API 令牌

从博客源码仓库(以下简称 “仓库1”)推送到外部 GitHub Pages 仓库(以下简称 “仓库2”),需要特定权限,所以还得在 GitHub 账户 Setting -> Developer settings -> Personal access tokens -> Tokens (Classic) -> Generate new token (classic) 创建一个 Token:

  1. 给 Token 备注一个名称,如:Token for Pages
  2. 到期时间:No expiration(永不过期)
  3. 范围选择:repoworkflow
  4. 生成令牌(Generate token)

5.1.3 配置环境变量

进入博客源码仓库的 Settings:

  1. 选择 “Secrets and variables” 下的 “Actions”,在 “Secrets” 选项卡中选择 “New repository secret” 项。
  2. 在 “Name” 中填入 PERSONAL_TOKEN,在 “Secret” 中填入前面生成的 token,点击 ”Add secret“ 保存。

5.1.4 创建工作流

返回源码仓库点击 “Actions” 按钮,搜索工作流 hugo ,找到后点击 “Configure”,修改后的配置内容如下(更详细用法参考 GitHub Pages action ):

 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
40
41
42
# Sample workflow for building and deploying a Hugo site to Github Pages
name: Deploy Hugo site to Pages

on:
  # 当这个项目仓库发生推送动作后,执行 GitHub Action
  push:
    branches: ["main"]
  # 可以在 GitHub 项目仓库的 Action 工具栏进行手动调用
  workflow_dispatch:

jobs:
    build:
        runs-on: ubuntu-latest
        steps:
            - name: Checkout
              uses: actions/checkout@v4.1.7
              with:
                  submodules: true
                  fetch-depth: 0

            - name: Setup Hugo
              uses: peaceiris/actions-hugo@v3
              with:
                  hugo-version: "latest"
                  # 按需选择是否使用 hugo-extended
                  extended: true

            - name: Build Web
              run: hugo

            - name: Deploy Web
              uses: peaceiris/actions-gh-pages@v4
              with:
                  # 生成的 token 就用在这里,因为下面用到 external repository
                  PERSONAL_TOKEN: ${{ secrets.PERSONAL_TOKEN }}
                  # 修改为你的 Github Pages 仓库
                  EXTERNAL_REPOSITORY: user/user.github.io
                  # 以及对应的分支 main/master
                  PUBLISH_BRANCH: main
                  # 指定将自动部署得到的 public 文件夹 push 上去
                  PUBLISH_DIR: ./public
                  commit_message: ${{ github.event.head_commit.message }}

5.1.5 推送更新

现在,可以在博客源码仓库中推送一片 .md 文章,GitHub Pages 仓库将同步更新,然后可以浏览 <username>.github.io (请替换为你的 URL)验证站点访问。

5.1.6 (可选)自定义域名

如果你使用了自定义域名,仅在 Github Pages 仓库的设置里配置域名是无效的,因为每次部署都会覆盖那里的设置。你需要通过 cname 指定:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
- name: Deploy Web
  uses: peaceiris/actions-gh-pages@v4
  with:
	  # 生成的 token 就用在这里,因为下面用到 external repository
	  PERSONAL_TOKEN: ${{ secrets.PERSONAL_TOKEN }}
	  # 修改为你的 Github Pages 仓库
	  EXTERNAL_REPOSITORY: user/user.github.io
	  # 以及对应的分支 main/master
	  PUBLISH_BRANCH: main
	  # 指定将自动部署得到的 public 文件夹 push 上去
	  PUBLISH_DIR: ./public
	  # 自定义域名  
	  cname: custom.domain.com
	  # 提交信息  
	  commit_message: ${{ github.event.head_commit.message }}

5.2 Cloudflare Pages 部署

Cloudflare Pages 更多集成部署请参考: Use Direct Upload with continuous integration

5.2.1 创建 Cloudflare Pages

  1. 登录 Cloudflare 仪表板。
  2. 在 “Workers 和 Pages” 菜单 -> Pages 中,“使用直接上传创建” -> 上传资产。为项目创建名称,如:blog

5.2.2 生成 API 令牌

要生成 API 令牌:

  1. 登录 Cloudflare 仪表板。
  2. 从仪表板右上角用户图标的下拉菜单中选择“我的个人资料”。
  3. 选择 API 令牌 > 创建令牌。
  4. 在“自定义令牌”下,选择“开始使用”。参考如下配置:👇

Pic_2024-07-24_140430.png

  1. 选择“继续显示摘要” > 创建令牌。

5.2.3 获取账户 ID

要查找您的账户 ID,请登录 Cloudflare 仪表板 > 在账户主页中选择您的区域 > 在右侧菜单 API 下的概览中查找您的账户 ID。如果您尚未添加区域,请通过选择“添加站点”来添加区域。您可以从 Cloudflare 的注册商处购买域名。

5.2.4 配置环境变量

进入 GitHub 博客源码仓库的 Settings:

  1. 选择 “Secrets and variables” 下的 “Actions”,在 “Secrets” 选项卡中选择 “New repository secret” 项。
  2. 在 “Name” 中填入 CLOUDFLARE_API_TOKEN,在 “Secret” 中填入 4.2.2 章节生成的 API Token ,点击 ”Add secret“ 保存。
  3. 以同样的方法创建 CLOUDFLARE_ACCOUNT_ID ,填入 4.2.3 章节获取的账户 ID 。

5.2.5 创建工作流

返回 GitHub 源码仓库点击 “Actions” 按钮,搜索工作流 hugo ,找到后点击 “Configure”,将 YOUR_PROJECT_NAME 替换为你的 Cloudflare Pages 项目名称。修改后的配置内容如下(更详细用法参考 Cloudflare Pages GitHub Action ):

 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
40
41
# Sample workflow for building and deploying a Hugo site to Cloudflare Pages
name: Deploy Hugo site to Cloudflare Pages

on:
  # 当这个项目仓库发生推送动作后,执行 GitHub Action
  push:
    branches: ["main"]
  # 可以在 GitHub 项目仓库的 Action 工具栏进行手动调用
  workflow_dispatch:

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      deployments: write
    name: Publish to Cloudflare Pages
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      # Run a build step here if your project requires

      - name: Publish to Cloudflare Pages
        uses: cloudflare/pages-action@v1.5
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          # Cloudflare Pages projects name
          projectName: YOUR_PROJECT_NAME
          # Publish directory
          directory: ./public
          # Optional: Enable this if you want to have GitHub Deployments triggered
          # gitHubToken: ${{ secrets.GITHUB_TOKEN }}
          # Optional: Switch what branch you are publishing to.
          # By default this will be the branch which triggered this workflow
          branch: main
          # Optional: Change the working directory
          # workingDirectory: my-site
          # Optional: Change the Wrangler version, allows you to point to a specific version or a tag such as `beta`
          wranglerVersion: '3'

5.2.6 推送更新

现在,可以在博客源码仓库中推送一片 .md 文章,GitHub Action 将自动把 public 目录下的 html 文件推送至 Pages 项目目录,然后可以浏览 Cloudflare Pages 为您提供的默认域名,如 blog.pages.dev (请替换为你的 URL)验证站点访问。

5.3 服务器部署

5.3.1 服务器准备

  1. 在远程服务器上创建站点存放目录。如:/var/www/blog/
  2. 在服务器上安装 rsync 工具。
  3. 服务器安全考虑,建议修改 SSH 远程连接端口(默认: 22)。
  4. SSH 用户准备,非 root 用户注意须赋予对站点目录读写权限。
  5. 为 SSH 用户生成密钥对,公钥部分应添加到服务器上的 authorized_keys 文件中。

5.3.2 Nginx 部署

  1. 根据服务器 OS 不同安装对应版本 nginx 应用。
  2. 若需要配置域名 SSL 证书,建议通过 acme.sh (github.com) 部署。

5.3.3 配置环境变量

进入博客源码仓库的 Settings:

  1. 选择 “Secrets and variables” 下的 “Actions”,在 “Secrets” 选项卡中选择 “New repository secret” 项。
  2. 为工作流中 remote_hostremote_portremote_userremote_path 等参数创建额外的 secret 。

5.3.4 创建工作流

在源码仓库点击 “Actions” 按钮,搜索工作流 hugo ,找到后点击 “Configure”,修改后的配置内容如下(更详细用法参考 Rsync Deployments Action ):

 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
40
41
42
43
44
45
46
47
48
49
# Sample workflow for building and deploying a Hugo site to Server
name: Deploy Hugo site to Server

on:
  # 当这个项目仓库发生推送动作后,执行 GitHub Action
  push:
    branches: ["main"]
  # 可以在 GitHub 项目仓库的 Action 工具栏进行手动调用
  workflow_dispatch:

jobs:
    build:
        runs-on: ubuntu-latest
        steps:
            - name: Checkout
              uses: actions/checkout@v4.1.7
              with:
                  submodules: true
                  fetch-depth: 0

            - name: Setup Hugo
              uses: peaceiris/actions-hugo@v3
              with:
                  hugo-version: "latest"
                  # 按需选择是否使用 hugo-extended
                  extended: true

            - name: Build Web
              run: hugo

            - name: Rsync Deployments
              uses: burnett01/rsync-deployments@7.0.1
              with:
                # rsync 同步选项
                switches: -avzr --delete
                # 本地仓库同步目录
                path: ./public/*
                # 远程仓库同步目录
                remote_path: ${{ secrets.DEPLOY_PATH }}
                # 远程服务器域名或IP
                remote_host: ${{ secrets.DEPLOY_HOST }}
                # 远程服务器端口
                remote_port: ${{ secrets.DEPLOY_PORT }}
                # 远程服务器用户
                remote_user: ${{ secrets.DEPLOY_USER }}
                # 远程服务器用户私钥
                remote_key: ${{ secrets.DEPLOY_KEY }}
                # 远程服务器用户私钥密码
                remote_key_pass: ${{ secrets.DEPLOY_KEY_PASS }}

5.3.5 推送更新

现在,可以在博客源码仓库中推送一片 .md 文章,GitHub Action 将自动把 public 目录下的 html 文件推送至远程服务器 /var/www/blog/ 站点目录,然后可以浏览你的远程服务器域名,如 blog.example.com (请替换为你的 URL)验证站点访问。

VI. 博客维护

6.1 开启评论组件(可选)

6.1.1 Waline

详细配置信息请参考: Waline

使用 Cloudflare CNAME 代理访问评论系统,Web 页面可能会出现重定向次数过多问题,请参考本教程 5.4.2 章节解决。

6.1.2 Giscus

详细配置信息请参考: giscus

6.2 升级主题

手动升级主题时,在站点目录下执行以下命令:

1
2
cd blog
git submodule update --remote

输入以下命令验证版本:

1
2
cd themes/hugo-theme-next/
git describe --tags

6.3 Hugo 常用命令

6.3.1 清除缓存

在开发环境中,有时缓存可能会导致问题。尝试清除 Hugo 缓存并重新生成站点:

1
hugo --cleanDestinationDir

6.3.2 调试日志

检查 Hugo 构建时的日志,看看是否有任何错误或警告信息:

1
hugo server -v

6.4 常见问题

6.4.1 新手问题

如果你是初次建站的话,可以使用 Github 的模板功能,一键生成你的站点仓库代码。访问 hugo-theme-next-starter 点击右上角的 Use this template 绿色按钮然后填写代码仓库的相关信息,详细参考 Hugo NexT 主题 README ,完成后克隆到本地测试,再根据个人喜好创建个性化配置。

6.4.2 重定向次数过多

参考文档: 访问后台出现重定向次数过多该怎么办 | CSDN

原因

Cloudflare 开启 SSL 证书后默认是灵活 SSL,仅在访问者与 Cloudflare 之间启用加密。这可以避免浏览器发出安全警告,但 Cloudflare 与您的源服务器之间的所有连接均通过 HTTP 建立。

解决方法

对于采用 Cloudflare 提供的 CDN 加速来说,将“灵活” SSL 切换到“完全” SSL。

VII. 参考文档

  1. 中文文档: Hugo 中文文档 (opendocs.io)

  2. 英文文档: Hugo Documentation | Hugo (gohugo.io)

  3. Hugo NexT 主题: hugo-next/hugo-theme-next(github.com)