I. 前提条件

1.1 安装 Hugo

1.1.1 Windows

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

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

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

1sysdm.cpl

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

1D:\Portable\Hugo

1.1.2 MacOS

1brew install hugo

1.1.3 Linux

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

1.1.4 确认安装

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

1hugo version

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

1.2 安装 Git

Git - Installing Git (git-scm.com)

II. 创建站点

2.1 安装确认

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

1hugo version

2.2 创建站点

  1. 在本地选择合适的站点存放路径。
  2. 在 Git Bash 中执行以下命令为站点创建目录结构
1# 将 blog 替换为您的网站名称
2hugo new site blog --format yaml

2.3 创建源码仓库

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

2.4 关联源码仓库

1cd blog
2git init -b main
3git remote add origin git@github.com:user/repo.git
4git pull --rebase origin main
5git add .
6git commit -m "Initial commit"
7git branch -M main
8git 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)” 页面布局(默认)。

1cd blog
2mv hugo.toml hugo.toml.bak
3git submodule add https://github.com/hugo-next/hugo-theme-next.git themes/hugo-theme-next
4cp themes/hugo-theme-next/exampleSite/hugo.yaml .
5mv hugo.toml hugo.toml.bak
6git 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 时自动更新子模块:

1git config submodule.recurse true

查看主题版本

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

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

3.3 站点信息

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

 1# 站点域名,比如: https://hugo-next.eu.org
 2# Website domain, eg: https://hugo-next.eu.org
 3baseURL: www.example.com
 4# 站点标题
 5# Website title
 6title: 小明的博客
 7
 8.....
 9#-----------------------------------------
10# Hugo NexT 主题参数配置
11# Configure Settings for Hugo NexT theme
12#-----------------------------------------
13params:
14  ......
15  
16  # 站点基本信息
17  # Site Information Settings
18  author: 小明
19  subtitle: 一个有趣的博客小站
20  description: 在这里记录我的喜怒哀乐。
21  keywords: IT,前端,Web
22
23  # 不同尺寸站点图标
24  # Different size of favicon
25  favicon:
26    icon: /imgs/icons/favicon.ico
27    small: /imgs/icons/favicon-16x16.png
28    medium: /imgs/icons/favicon-32x32.png
29    appleTouchIcon: /imgs/icons/apple-touch-icon.png

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

3.4 自定义菜单

  1. 示例菜单一般都需要重新配置,以下配置项按实际增减
 1menus:
 2  main:
 3    - identifier: home
 4      name: 首页
 5      pageRef: /
 6      pre: home
 7      weight: 1
 8    - identifier: tech
 9      name: 技术
10      pageRef: /tech
11      pre: screwdriver-wrench
12      weight: 2
13    - identifier: live
14      name: 生活
15      pageRef: /live
16      pre: umbrella-beach
17      weight: 3
18    - identifier: about
19      name: 关于
20      pageRef: /about
21      pre: user
22      weight: 4
23    - identifier: flinks
24      name: 友链
25      pageRef: /flinks
26      pre: thumbs-up
27      weight: 5
28    - identifier: commonweal
29      name: 公益
30      pageRef: /404.html
31      pre: heartbeat
32      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 )👇
1params:
2  # 需要显示文章的部分,即content目录下的文件夹名称
3  # Sections for show in home & archive page 
4  # and it's forlder name which under content
5  mainSections: ["tech", "live"]
6  ......
  1. 还需创建实际文章存放目录(Discussion #47
1mkdir content/{tech,live}

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

3.5 多语言(可选)

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

 1languages:
 2  zh-cn:
 3    languageCode: zh-CN
 4    languageDirection: ltr
 5    languageName: "简体中文"
 6    weight: 1    
 7  en-us:
 8    languageCode: en-US
 9    languageDirection: ltr
10    languageName: English
11    weight: 2
12    menus:
13      main:
14        - identifier: home
15          name: Home
16          pageRef: /
17          pre: home
18          weight: 1
19        - identifier: about
20          name: About
21          pageRef: /about.html
22          pre: user
23          weight: 2
24        - identifier: flinks
25          name: Friend's Links
26          pageRef: /flinks.html
27          pre: thumbs-up
28          weight: 3
29        - identifier: example
30          name: Example
31          pre: angles-down
32          weight: 4
33        - identifier: syntax
34          name: Syntax Highlighting
35          pageRef: /post/09-syntax-highlighting
36          weight: 1   
37          parent: example
38        - identifier: math
39          name: Math Formula
40          pageRef: /post/10-math-formula
41          weight: 2   
42          parent: example
43          parent: example
44        - identifier: flow-charts
45          name: Flow Charts
46          pageRef: /post/11-mermaid-charts
47          weight: 3
48          parent: example
49        - identifier: archives
50          name: Archives
51          pageRef: /archives
52          pre: archive
53          weight: 5
54        - identifier: commonweal
55          name: Commonweal404
56          pageRef: /404.html
57          pre: heartbeat
58          weight: 6
59    params:
60      yearFormat: "2006"
61      monthFormat: "01/02"
62      dateFormat: "2006/01/02"
63      timeFormat: "2006/01/02 15:04:05 -07:00"
64
65      author: NexT Theme
66      subtitle: Build for Hugo Theme
67      description: Keep it simple, keep it powerful.
68      keywords: Hugo,NexT,theme,simple,powerful
69
70      linksSets:
71        title: Links
72      
73      footer:
74        beian:
75          enable: false
76      
77      postFooter:
78        endLineTip: "~ End Line ~"
79      
80      rewardSets:
81        comment: '<i class="fa-solid fa-mug-hot"></i>  How about you buy me a coffee?ヾ(^▽^*)))'

3.6 侧边栏

3.6.1 头像更换

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

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # 侧边栏头像
 9  # Sidebar Avatar
10  avatar:
11    # 设置显示头像的相对路径
12    # Replace the default image and set the url here.
13    url: /imgs/icons/avatar.png

3.6.2 日志重命名(可选)

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

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

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

1Sidebar:
2  label:
3    posts: 文章
4    ......
5
6Terms:
7  archives: "目前共计 <strong>{{ .Count }}</strong> 篇文章"
8  ......

3.7 站点统计(可选)

  1. 注册 51la 账号

  2. 修改站点配置

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  siteState: 
 9    # 是否在侧边栏显示文章、分类、标签信息
10    # Posts / Categories / Tags in sidebar.
11    basic: true
12    # 站点访问信息
13    # Site's view information
14    views:  
15      enable: true
16      # 组件类型,可选值为: 51la, busuanzi
17      # 使用51la时需要注册账号:https://invite.51.la/
18      # Plguin value is: 51la, busuanzi
19      plugin: 51la
20  ......
21  
22  analytics:
23    # 51La 站点统计
24    # 更多信息请参考:https://invite.51.la/1NUfGTS1?target=V6
25    # 51La Analytics
26    # See: https://invite.51.la/1NUfGTS1?target=V6 
27    #laId: #<anaytics_id> 
28    laId: 123456789ABCDEFG
29    # 百度统计
30    # Baidu Analytics
31    #baidu: #<anaytics_id>
32    # 谷歌统计
33    # Google Analytics
34    #google: #<anaytics_id>
35    # 不蒜子统计
36    # Show Views / Visitors of the website / page with busuanzi.
37    # For more information: http://ibruce.info/2015/04/04/busuanzi/
38    #busuanzi:
39    #  visitorsIcon: fa fa-user
40    #  viewsIcon: fa fa-eye

3.8 文章展示(可选)

3.8.1 标题边框

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

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

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

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

3.8.2 数学公式渲染

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

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

3.9 其它配置(可选)

3.9.1 友情链接

根据需求修改或删除:

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # 友情链接地址
 9  # 用法: `Key: 显示名称 || 链接地址`
10  # Links of your friends
11  # Usage: `Key: name || permalink`
12  links: 
13    link0: Hugo-NexT || https://gitee.com/hugo-next/hugo-theme-next
14    link1: 凡梦星尘空间站 || https://lisenhui.cn

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

3.9.2 标题序号

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

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

3.9.3 社交链接

按需修改:

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  socials: 
 9    social0: Github || https://github.com/elkan1788 || fab fa-github
10    #social1: E-Mail || mailto:yourname@gmail.com || fa fa-envelope
11    social2: 知乎 || https://www.zhihu.com/people/lisenhui || fa fa-book
12    #Google: https://plus.google.com/yourname || fab fa-google
13    ......

3.9.4 备案和供应商

按需修改:

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # ---------------------------------------------------------------
 9  # 站点底部设置
10  # Footer Settings
11  # ---------------------------------------------------------------
12  footer:    
13    ......
14
15    # 国内 ICP 备案和公安网备信息
16    # Beian ICP and gongan information for Chinese users. 
17    # See: https://beian.miit.gov.cn, http://www.beian.gov.cn
18    beian:
19      enable: false
20      ......
21
22    # 站点支持供应商列表
23    # Vendors list who support website. 
24    vendors:
25      enable: false
26      ......

3.9.5 捐赠

按需修改:

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # 捐赠信息设置
 9  # Donate (Sponsor) settings.
10  rewardSets:
11    # 是否开启捐赠按钮,开启后将在每个文章页面底部显示
12    # If true, a donate button will be displayed 
13    # in every article by default.
14    enable: false
15    ......

3.9.6 订阅

按需修改:

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # 提供其它订阅站点文章的方式
 9  # 用例: `key: 名称 || 链接(图像地址)|| icon名称`
10  # Subscribe through Telegram Channel, Twitter, etc.
11  # Usage: `Key: name || permalink || icon` (Font Awesome)
12  followMe:
13    #channel0: Twitter || https://twitter.com/username || fab fa-twitter
14    #channel1: Telegram || https://t.me/channel_name || fab fa-telegram
15    channel2: WeChat || /images/wechat_channel.jpg || fab fa-weixin
16    channel3: RSS || /atom.xml || fa fa-rss

3.9.7 在线编辑

按需修改:

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # 文章的在线编辑
 9  # Post edit
10  # Easily browse and edit blog source code online.
11  postEdit:
12    enable: false
13    url: https://github.com/user-name/repo-name/tree/branch-name/subdirectory-name/

3.9.8 GitHub 关注

按需修改:

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # 右上角在 Github 上面关注我的横幅
 9  # `Follow me on GitHub` banner in the top-right corner.
10  githubBanner:
11    # 是否开启显示
12    # If true, will display banner.
13    enable: false
14    ......

3.9.9 评论组件

按需修改:

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # 评论组件设置,最多支持2个显示
 9  # Multiple Comment System Support
10  comments:
11    # 开启评论组件
12    # If true, will show comment component in post end.
13    enable: false   
14    ......

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

 1#-----------------------------------------
 2# Hugo NexT 主题参数配置
 3# Configure Settings for Hugo NexT theme
 4#-----------------------------------------
 5params:
 6  ......
 7
 8  # 开启文章头部元素显示
 9  # Post meta display settings
10  postMeta:
11    ......
12
13    # 是否开启评论数显示
14    comments: 
15      enable: true
16      # 评论统计插件,暂只支持waline和waline3
17      # Comment counter plugin, only support waline and waline3
18      plugin: waline3
19    # 是否开启页面访问数显示
20    views:
21      enable: true
22      # 页面访问统计插件,支持busuanzi, waline, waline3
23      # Page views counter plugin, support: busuanzi, waline, waline3
24      plugin: waline3

IV. 创建文章

4.1 配置文章模板

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

4.2 发布文章

4.2.1 创建文章

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

4.2.2 增加前置格式

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

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

📌 参数说明:

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

4.3 本地开发调试

显示草稿内容并禁用快速渲染,通过以下命令在本地实时预览当前编辑内容:

1hugo server -D --disableFastRender

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

4.4 生产环境部署

清空现有 public 目录所有文件,重新构建整个网站,压缩优化所有生成的文件:

1hugo --cleanDestinationDir --minify

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# Sample workflow for building and deploying a Hugo site to Github Pages
 2name: Deploy Hugo site to Github Pages
 3
 4on:
 5  push:
 6    branches:
 7      # 设置分支名称以触发部署
 8      - main
 9  workflow_dispatch:
10
11jobs:
12  deploy:
13    runs-on: ubuntu-latest
14    permissions:
15      contents: write
16    concurrency:
17      group: ${{ github.workflow }}-${{ github.ref }}
18      # 只保留最新一次构建,自动取消旧构建
19      cancel-in-progress: true
20    steps:
21      - name: Checkout
22        uses: actions/checkout@v6
23        with:
24          # 同时拉取 Git 子模块
25          submodules: true
26          # 完整拉取 Git 历史,而不是浅克隆
27          fetch-depth: 0
28
29      - name: Setup Hugo
30        uses: peaceiris/actions-hugo@v3
31        with:
32          hugo-version: 'latest'
33          # 按需选择是否使用 hugo-extended
34          extended: true
35
36      - name: Build
37        run: hugo --minify
38
39      - name: Deploy
40        uses: peaceiris/actions-gh-pages@v4
41        # 只有在 main 分支触发时,才执行发布
42        if: github.ref == 'refs/heads/main'
43        with:
44          # 生成的 token 就用在这里,因为下面用到 external repository
45          personal_token: ${{ secrets.PERSONAL_TOKEN }}
46          # 修改为你的 Github Pages 仓库
47          external_repository: user/user.github.io
48          # 以及对应的分支 main/master
49          publish_branch: main
50          # 指定将自动部署得到的 public 文件夹 push 上去
51          publish_dir: ./public
52          # 避免旧文件残留
53          keep_files: false
54          # 提交信息
55          commit_message: ${{ github.event.head_commit.message }}

5.1.5 推送更新

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

5.1.6 (可选)自定义域名

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

 1- name: Deploy
 2  uses: peaceiris/actions-gh-pages@v4
 3  # 只有在 main 分支触发时,才执行发布
 4  if: github.ref == 'refs/heads/main'
 5  with:
 6    # 生成的 token 就用在这里,因为下面用到 external repository
 7    personal_token: ${{ secrets.PERSONAL_TOKEN }}
 8    # 修改为你的 Github Pages 仓库
 9    external_repository: user/user.github.io
10    # 以及对应的分支 main/master
11    publish_branch: main
12    # 指定将自动部署得到的 public 文件夹 push 上去
13    publish_dir: ./public
14    # 避免旧文件残留
15    keep_files: false
16    # 自定义域名
17    cname: blog.example.com
18    # 提交信息
19    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_20250326_083010.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# Sample workflow for building and deploying a Hugo site to Cloudflare Pages
 2name: Deploy Hugo site to Cloudflare Pages
 3
 4on:
 5  # 当这个项目仓库发生推送动作后,执行 GitHub Action
 6  push:
 7    branches: ["main"]
 8  # 可以在 GitHub 项目仓库的 Action 工具栏进行手动调用
 9  workflow_dispatch:
10
11jobs:
12  publish:
13    runs-on: ubuntu-latest
14    permissions:
15      contents: read
16      deployments: write
17    name: Publish to Cloudflare Pages
18    steps:
19      - name: Checkout
20        uses: actions/checkout@v4
21
22      # Run a build step here if your project requires
23
24      - name: Publish to Cloudflare Pages
25        uses: cloudflare/pages-action@v1.5
26        with:
27          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
28          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
29          # Cloudflare Pages projects name
30          projectName: YOUR_PROJECT_NAME
31          # Publish directory
32          directory: ./public
33          # Optional: Enable this if you want to have GitHub Deployments triggered
34          # gitHubToken: ${{ secrets.GITHUB_TOKEN }}
35          # Optional: Switch what branch you are publishing to.
36          # By default this will be the branch which triggered this workflow
37          branch: main
38          # Optional: Change the working directory
39          # workingDirectory: my-site
40          # Optional: Change the Wrangler version, allows you to point to a specific version or a tag such as `beta`
41          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# Sample workflow for building and deploying a Hugo site to Server
 2name: Deploy Hugo site to Server
 3
 4on:
 5  # 当这个项目仓库发生推送动作后,执行 GitHub Action
 6  push:
 7    branches: ["main"]
 8  # 可以在 GitHub 项目仓库的 Action 工具栏进行手动调用
 9  workflow_dispatch:
10
11jobs:
12    build:
13        runs-on: ubuntu-latest
14        steps:
15            - name: Checkout
16              uses: actions/checkout@v4.1.7
17              with:
18                  submodules: true
19                  fetch-depth: 0
20
21            - name: Setup Hugo
22              uses: peaceiris/actions-hugo@v3
23              with:
24                  hugo-version: "latest"
25                  # 按需选择是否使用 hugo-extended
26                  extended: true
27
28            - name: Build Web
29              run: hugo
30
31            - name: Rsync Deployments
32              uses: burnett01/rsync-deployments@7.0.1
33              with:
34                # rsync 同步选项
35                switches: -avzr --delete
36                # 本地仓库同步目录
37                path: ./public/*
38                # 远程仓库同步目录
39                remote_path: ${{ secrets.DEPLOY_PATH }}
40                # 远程服务器域名或IP
41                remote_host: ${{ secrets.DEPLOY_HOST }}
42                # 远程服务器端口
43                remote_port: ${{ secrets.DEPLOY_PORT }}
44                # 远程服务器用户
45                remote_user: ${{ secrets.DEPLOY_USER }}
46                # 远程服务器用户私钥
47                remote_key: ${{ secrets.DEPLOY_KEY }}
48                # 远程服务器用户私钥密码
49                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 升级主题

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

1cd blog
2git submodule update --remote

输入以下命令验证版本:

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

6.3 Hugo 常用命令

6.3.1 清除缓存

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

1hugo --cleanDestinationDir

6.3.2 调试日志

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

1hugo 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)