之前使用wordpress记录博客,依赖php,占用资源挺多的,在搬瓦工vps上运行也谈不上快,最主要的是申请的tk域名不会被搜索引擎引用,这次借着重装vps,优化流程,就把博客迁移到了github上,下面记录一下过程。

众所周知,github pages提供了静态网站的能力,而blog一般是Markdown格式的,Markdown转静态网页的解决方案很多,Jekyll,hugo,Hexo是其中的佼佼者,综合考虑,这次选择了hugo,它是go语言开发的,天生没有依赖,转换速度也最快。

首先在github上新建2个仓库,blog和[用户名].github.io,前者为私有仓库,用于保存hugo站点+Markdown文件,后者为public仓库(github pages要求必须是public仓库),保存转换好的静态网页。提交到blog仓库的修改设置触发github actions,自动执行hugo将Markdown转换成静态网页,再提交到[用户名].github.io,这样日后只用维护blog这个仓库就行。

部署hugo

hugo基于go语言开发,就一个可执行文件,根据当前系统类型,从hugo github release下载相应的可执行文件到系统可执行路径即可。

生成站点

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# hugo new site blog
# cd blog
# tree
.
├── archetypes
│   └── default.md
├── config.toml
├── content
├── data
├── layouts
├── static
└── themes

6 directories, 2 files
# git init

config.toml 是配置文件,在里面可以定义博客地址、构建配置、标题、导航栏等等。 themes 是主题目录,可以去 themes.gohugo.io 下载喜欢的主题。 content 是博客文章的目录。

添加主题

themes.gohugo.io 选择喜欢的主题,下载到 themes 目录中,然后在 config.toml 中配置 theme = "even" 即可。

1
2
3
# git clone https://github.com/olOwOlo/hugo-theme-even themes/even  # 下载主题
# rm -rf themes/even/.git  # 清理主题git
# cp themes/even/exampleSite/config.toml .  # 复制主题配置

根据个人需要,调整config.toml文件内容

忽略public目录

hugo生成的静态网页放在public目录,这个目录无需提交到blog仓库,添加.gitignore文件忽略

1
2
# cat ~/blog/.gitignore 
public

github action自动发布

生成发布key

1
2
3
4
ssh-keygen -t rsa -b 4096 -C "$(git config user.email)" -f gh-pages -N ""
# You will get 2 files:
#   gh-pages.pub (public key)
#   gh-pages     (private key)

把公钥设置到[用户名].github.io仓库的Deploy Keys,记得选上写权限,私钥设置到blog仓库的Secrets,名字叫ACTIONS_DEPLOY_KEY

github action

新建.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
# cat .github/workflows/deploy.yml 
name: deploy hugo blog github action

# 当master分支发生push事件时执行下面任务
on:
  push:
    branches:
      - master

jobs:
  build-deploy:
    runs-on: ubuntu-18.04
    steps:
    - uses: actions/checkout@v2
      with:
        submodules: true
        fetch-depth: 0

    - name: Setup Hugo
      uses: peaceiris/actions-hugo@v2
      with:
        hugo-version: 'latest'

    - name: Build
      run: hugo -t even

    - name: Deploy
      uses: peaceiris/actions-gh-pages@v3
      with:
        deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }}
        external_repository: carter2005/carter2005.github.io
        publish_branch: master
        publish_dir: ./public

这样,只要在content/post下面新增Markdown文件博客,提交后,github会自动调用最新版本的hugo转换并提交到[用户名].github.io仓库。