用Hugo构建新博客
跟熊壕合租的服务器忘了续费,以前的博客没了。索性来用免费的Github Pages,而静态网站生成器则用Hugo。当然,Cloudflare也要继续用。
使用静态网站生成器+Github Pages有很多种方式,有的是将整个博客的源码和生成后的内容都放在一个分支下,以目录区分,有的是用两个分支(比如master和gh-pages)。但是做了一些功课之后,我选择将源码和生成的内容保存在两个repo,并将“生成”这一步交给Github Actions。
准备Github Repository
创建Repository
在Github上创建两个repo:
- 一个用来存储Github Pages,名字是
username.github.io
,例如我的是dantewang.github.io
- 一个用来存储Hugo网站的源文件,可以是private的,名字随意
配置Actions
参考Github提供的教程,创建SSH Key:
ssh-keygen -t ed25519 -C "[email protected]" -f path/to/file
这里指定了不同的路径和文件名,以免覆盖git
命令用来连接Github的Key。
然后,分别配置两个repo:
- 在Github Pages repo的 Settings -> Deploy Key 中 Add new secrets,填入公钥文件(*.pub)的内容
- 在Hugo源文件repo的 Settings -> Secrets 中 Add new secrets,取名为
ACTIONS_DEPLOY_KEY
,填入私钥文件的内容
git clone
第二个repo,添加.github/workflows/gh_pages.yml
,内容如下:
name: hugo publish
on:
push:
branches:
- master
jobs:
build-deploy:
runs-on: ubuntu-18.04
steps:
- uses: actions/[email protected]
with:
submodules: true
fetch-depth: 0
- name: Setup Hugo
uses: peaceiris/[email protected]
with:
hugo-version: 'latest'
extended: true
- name: Build
run: hugo --minify
- name: Deploy
uses: peaceiris/[email protected]
with:
deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }} # 对应前面创建的secret
external_repository: dantewang/dantewang.github.io
publish_dir: ./public
publish_branch: master
cname: dante.io # 自动创建CNAME文件用来绑定域名
allow_empty_commit: false
commit_message: ${{ github.event.head_commit.message }}
用Hugo创建网站
安装extended版本的Hugo,这里我用scoop来安装:
scoop install hugo-extended
在之前clone的repo的目录里,创建新的Hugo网站:
hugo new site .
然后安装一个主题,这里我选择了PaperMod:
git submodule add https://github.com/adityatelange/hugo-PaperMod.git themes/PaperMod
最后新建一篇日志,并且随便写点儿什么:
hugo new posts/hello-world.md
可以通过 hugo server -D
在本地预览网站。没有问题的话,就将Hugo源文件repo里的改动提交,push到Github。Repo里配置的Action会自动运行,一会儿就能在“Actions”标签页里看到自动构建的情况了。
配置Cloudflare
构建成功之后,Github Pages Repo的Settings里面的Enforce HTTPS却还不能选。因为绑定了域名,必须要绑定生效,Github才会去签发证书。
到Cloudflare的控制面板里,删除原来的解析条目,然后根据Github Pages文档里的说明,添加4条A记录到文档里提供的4个IP。这样之后,我的网站还是不能访问,即使在Cloudflare中关闭对源服务器的HTTPS认证也不行,而Github Pages repo里的Enforce HTTPS也一直处于不可选的状态。
搜索之后发现,为了让Github能开始配置HTTPS,需要先关掉Cloudflare的CDN Proxy——将解析记录上的“Proxy”(一朵云的图标)点成灰色。这样等待一段时间之后,Github就会配置好HTTPS,Enforce HTTPS就会变为可选项。选中之后,就可以重新启动CDN Proxy了。
参考资料
关于Github Actions的配置
Automate your GitHub Pages Deployment using Hugo and Actions
Generating a new SSH key and adding it to the ssh-agent
Github Action Marketplace: Hugo setup
Github Action Marketplace: GitHub Pages action
关于Hugo
hugo-PaperMod Wiki: Installation
关于绑定域名和Cloudflare
Managing a custom domain for your GitHub Pages site: Configuring an apex domain
Custom domains, GH-pages, Cloudflare and strict SSL end-to-end encryption