为 GitHub Pages 建立 Hugo 博客的一种好方法是使用两个独立的存储库:
- 第一个存储库包含博客源,
- 第二个存储库包含生成的内容。
命名第二个存储库 username.github.io
(使用您的 GitHub 用户名)。GitHub Pages 会自动将其部署到https://username.github.io/。
然后将第二个存储库作为 git 子模块添加到第一个存储库。子模块需要位于./public
,这是 Hugo 生成静态内容的地方。这使您可以轻松地将生成的内容推送到 GitHub。
git submodule add \
https://github.com/username/username.github.io.git \
public
这个过程在官方 Hugo 教程Hosting on GitHub中有更详细的解释。
持续集成
如果您想要完全自动化,您可以为第一个存储库设置 Travis CI。我在这里写了一篇关于这个设置的详细文章:
使用 Travis CI 在 Github 页面上托管 Hugo 博客
Travis CI 调用 Hugo 并将生成的内容推送回 GitHub,由 GitHub Pages 部署。为此,您需要一个.travis.yml
文件和一个小型部署脚本:
.travis.yml
---
install:
- curl -LO https://github.com/gohugoio/hugo/releases/download/v0.55.4/hugo_0.55.4_Linux-64bit.deb
- sudo dpkg -i hugo_0.55.4_Linux-64bit.deb
script:
- hugo
deploy:
- provider: script
script: ./deploy.sh
skip_cleanup: true
on:
branch: master
部署.sh
#!/bin/bash
echo -e "\033[0;32mDeploying updates to GitHub...\033[0m"
cd public
if [ -n "$GITHUB_AUTH_SECRET" ]
then
touch ~/.git-credentials
chmod 0600 ~/.git-credentials
echo $GITHUB_AUTH_SECRET > ~/.git-credentials
git config credential.helper store
git config user.email "username@users.noreply.github.com"
git config user.name "username"
fi
git add .
git commit -m "Rebuild site"
git push --force origin HEAD:master
最后,在 Travis CI 上设置一个环境变量GITHUB_AUTH_SECRET
以提供对username.github.io
存储库的访问。博客文章还解释了如何为此使用单独的机器人帐户,限制 CI 对username.github.io
存储库的访问。