博客自动化部署配置记录

一、整体思路

我的博客源码在本地,GitHub 上有一个已经部署好的 Pages 仓库(flechazoyang-google.github.io)。我希望实现:本地写文章 → Git 提交 → GitHub Actions 自动构建 → 网站自动更新。

二、前期准备

2.1 创建源码仓库

在 GitHub 上新建了一个私有仓库 hexo-blog-source,用来存放 Hexo 源码(主题、文章等)。

2.2 生成 Personal Access Token

在 GitHub Settings → Developer settings → Fine-grained tokens 中创建了一个 token:

  • Token name: blog-deploy-token
  • Repository access: Only select repositories,选中 Pages 仓库 flechazoyang-google.github.io
  • Permissions: Contents 设置为 Read and write

⚠️ 注意:token 生成后只显示一次,一定要立即复制保存。

三、遇到的问题及解决

问题 1:Git 用户名搞混了

我的 GitHub 用户名是 flechazoyang-google,但仓库地址里写成了 flechazoyang-github,导致推送失败。

解决方法:用 git remote set-url 修正远程地址。

1
git remote set-url origin https://github.com/flechazoyang-google/hexo-blog-source.git

问题 2:本地分支是 master,远程需要 main

本地默认分支是 master,但 GitHub 新建仓库默认分支是 main,直接 git push 报错。

解决方法:推送时指定本地分支和远程分支的对应关系。

1
git push -u origin master:main

问题 3:网络连接失败

第一次推送时报错:fatal: unable to access ... Recv failure: Connection was reset

解决方法:改用 SSH 方式推送。

1
2
git remote set-url origin git@github.com:flechazoyang-google/hexo-blog-source.git
git push -u origin master:main

问题 4:第一次 Actions 运行较慢

第一次部署需要下载环境、安装依赖,花了大概 5 分钟。后续有了缓存就会快很多。

四、最终配置

4.1 添加 Secret

在源码仓库 hexo-blog-source → Settings → Secrets → Actions 中添加:

  • Name: PAGES_TOKEN

  • Value: 之前生成的 token

4.2 创建工作流文件

在源码仓库中创建 .github/workflows/deploy.yml

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
name: Build and Deploy Hexo
on:
push:
branches:
- main
workflow_dispatch:
permissions:
contents: read
concurrency:
group: hexo-deploy
cancel-in-progress: true
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Generate static files
run: |
npx hexo clean
npx hexo generate
- name: Deploy to Pages repository
uses: peaceiris/actions-gh-pages@v4
with:
personal_token: ${{ secrets.PAGES_TOKEN }}
external_repository: flechazoyang-google/flechazoyang-google.github.io
publish_branch: main
publish_dir: ./public
commit_message: "deploy: ${{ github.sha }}"

五、最终效果

  • ✅ 本地 git push 后,GitHub Actions 自动运行

  • ✅ 构建成功后,静态文件自动推送到 Pages 仓库

  • ✅ 网站自动更新,约 1-2 分钟生效

六、日常发文流程

1
2
3
4
5
6
7
# 1. 写文章(在 source/_posts/ 目录下)

# 2. 提交并推送

git add .
git commit -m "发布新文章:xxx"
git push

后续 git push 已经可以直接使用,不需要每次都写 master:main