Hexo + GitHub Pages 博客搭建避坑指南

一、主题配置

1.1 修改主题后页面不刷新

Hexo 不支持热更新。每次改配置或模板后必须重新构建:

1
hexo clean && hexo g

本地预览 hexo s 可以看到效果,部署前务必先本地确认。

1.2 <br> 在 EJS 模板中不换行

EJS 模板里用 <%= 会转义 HTML,换行符 <br> 会变成 &lt;br&gt;。需要换行显示时用 <%-

1
2
3
4
5
<!-- ✗ 不换行 -->
<%= profile.author_title %>

<!-- ✓ 正常换行 -->
<%- profile.author_title %>

1.3 分类页和友链页需要手动创建

主题有菜单不代表对应页面会自己出现。需要手动在 source/ 下创建:

1
2
source/categories/index.md  → layout: categories
source/links/index.md → type: links

分类页的关键是 layout: categories(不是 type: categories),否则页面只有空白。


二、数学公式

2.1 Markdown 渲染器冲突

hexo-renderer-marked 会把 LaTeX 的 \\ 转成 <br>\begin{aligned} 等环境会损坏。数学内容多的博客建议用 hexo-renderer-kramed,对特殊符号更友好。

2.2 MathJax 默认不加载

主题的 MathJax 可能绑定了 page.mathjax 开关,需要手动在 frontmatter 里加 mathjax: true

更彻底的做法:在 script.ejs 中全站加载 MathJax 3 CDN,一劳永逸。


三、图片资源

3.1 图片放在 _posts/ 下不会复制到 public/

Hexo 不识别 .webp 等非文本格式为静态资源。解决方案:

  1. 图片放入 source/ 根目录下的独立文件夹(如 source/attachment/
  2. _config.yml 配置:
1
2
skip_render:
- "attachment/**"
  1. 文中用 ![](/attachment/xxx.webp) 引用

四、URL 与域名

4.1 全站链接变成 http://example.com

博客根目录 _config.yml 里的 url 字段控制所有链接前缀,必须改成自己的域名:

1
url: https://your-domain.com

4.2 GitHub Pages 自定义域名

  1. source/ 下创建 CNAME 文件,内容为你的域名
  2. DNS 添加 CNAME 记录指向 username.github.io
  3. 部署后 GitHub Pages Settings 里确认域名已生效

五、评论系统

5.1 Gitalk 403 问题

Gitalk 需要把 clientSecret 暴露在前端 HTML 中,GitHub 检测到纯前端暴露 OAuth 密钥会直接拒绝请求 → 403 无解。

解决方案:换成 utterances

5.2 utterances 配置

  1. 模板添加 utterances.ejs,挂载 https://utteranc.es/client.js
  2. _config.yml 配置三个参数:
1
2
3
4
5
6
comment:
type: utterances
utterances:
repo: username/repo
issue_term: pathname
theme: github-light
  1. 最重要的一步:去 https://github.com/apps/utterances → Install → 授权仓库

忘记安装 App 会导致页面报 “utterances is not installed”,没有评论框。

5.3 评论系统选择建议

系统 是否需要密钥 认证方式 推荐度
utterances GitHub App ⭐推荐
Giscus GitHub App ⭐推荐
Gitalk OAuth App 不推荐(密钥暴露)
Valine LeanCloud 需注册第三方

六、HTTPS 推送认证

6.1 Error: Spawn failed

GitHub 已禁用 HTTPS 密码登录。如果是老仓库,_config.yml 的 deploy repo 可能还配着 https://github.com/...

修复:改为 SSH 地址,前提是本地已配置 SSH key 并添加到 GitHub:

1
2
3
4
deploy:
type: git
repo: git@github.com:username/repo.git
branch: your-branch

6.2 环境变量持久化(Windows)

setx 写入的变量只对新打开的终端生效,当前终端需要手动 export 或用新窗口。

GitHub Pages 部署时不需要环境变量——hexo g 阶段已经把值写死进 HTML 了,推送的是静态文件。


七、部署流程

1
2
3
4
5
6
7
# 确保环境变量已加载(如需要)
export YOUR_SECRET="xxx"

# 三步推送
hexo clean
hexo g
hexo d

改代码 → 改配置 → 本地预览 → clean + g + d 三连。别跳过 clean,残留文件是隐蔽故障的常见来源。


八、博客文件结构参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
hexo-blog/
├── _config.yml # 博客根配置(url、deploy、主题名)
├── source/
│ ├── CNAME # 自定义域名
│ ├── _posts/ # 文章 .md
│ ├── _data/links.yml # 友链数据
│ ├── attachment/ # 静态图片等
│ ├── about/index.md # 关于页
│ ├── books/index.md # 书单页
│ ├── categories/index.md
│ └── links/index.md
└── themes/
└── your-theme/
├── _config.yml # 主题配置
├── layout/ # EJS 模板
├── source/ # 主题静态资源
└── scripts/ # 辅助脚本