部署发布
Hugo 生成的静态网站可以部署到几乎任何托管平台。本章将介绍主流的部署方式和最佳实践。
部署方式概览
Hugo 网站的部署方式可以分为以下几类:
托管平台:提供持续集成和自动部署的服务
- GitHub Pages:免费,与 GitHub 深度集成
- Netlify:功能丰富,支持表单和函数
- Cloudflare Pages:全球 CDN,免费额度大
- Vercel:极速部署,支持 Serverless
- Render:简单易用,支持多种语言
- Firebase Hosting:Google 生态,适合移动应用
云存储:适合静态文件托管
- AWS S3
- Azure Blob Storage
- Google Cloud Storage
传统服务器:需要手动配置
- rsync 同步
- rclone 同步
- FTP 上传
Hugo 内置部署:直接使用 hugo deploy 命令
GitHub Pages
GitHub Pages 是最受欢迎的免费静态网站托管服务之一,与 GitHub 仓库深度集成,支持自动构建和部署。
站点类型
GitHub Pages 支持三种类型的站点:
| 类型 | URL 格式 | 说明 |
|---|---|---|
| 用户站点 | username.github.io | 使用 username.github.io 仓库 |
| 组织站点 | orgname.github.io | 使用 orgname.github.io 仓库 |
| 项目站点 | username.github.io/repo | 使用任意仓库 |
准备工作
在开始之前,请确保:
- 已创建 GitHub 账户
- 已创建 GitHub 仓库
- 本地 Git 仓库已关联远程仓库
- Hugo 站点已创建并本地测试通过
配置缓存目录
首先在站点配置中设置缓存目录:
[caches]
[caches.images]
dir = ':cacheDir/images'
这确保图片缓存存储在正确的位置,避免权限问题。
创建 GitHub Actions 工作流
在项目根目录创建 .github/workflows/hugo.yaml 文件:
name: Build and deploy
on:
push:
branches:
- main
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
defaults:
run:
shell: bash
jobs:
build:
runs-on: ubuntu-latest
env:
DART_SASS_VERSION: 1.93.2
GO_VERSION: 1.25.3
HUGO_VERSION: 0.152.2
NODE_VERSION: 22.20.0
TZ: Asia/Shanghai
steps:
- name: Checkout
uses: actions/checkout@v5
with:
submodules: recursive
fetch-depth: 0
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
cache: false
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- name: Setup Pages
id: pages
uses: actions/configure-pages@v5
- name: Create directory for user-specific executable files
run: |
mkdir -p "${HOME}/.local"
- name: Install Dart Sass
run: |
curl -sLJO "https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz"
tar -C "${HOME}/.local" -xf "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz"
rm "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz"
echo "${HOME}/.local/dart-sass" >> "${GITHUB_PATH}"
- name: Install Hugo
run: |
curl -sLJO "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
mkdir "${HOME}/.local/hugo"
tar -C "${HOME}/.local/hugo" -xf "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
rm "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
echo "${HOME}/.local/hugo" >> "${GITHUB_PATH}"
- name: Verify installations
run: |
echo "Dart Sass: $(sass --version)"
echo "Go: $(go version)"
echo "Hugo: $(hugo version)"
echo "Node.js: $(node --version)"
- name: Install Node.js dependencies
run: |
[[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci || true
- name: Configure Git
run: |
git config core.quotepath false
- name: Cache restore
id: cache-restore
uses: actions/cache/restore@v4
with:
path: ${{ runner.temp }}/hugo_cache
key: hugo-${{ github.run_id }}
restore-keys: hugo-
- name: Build the site
run: |
hugo \
--gc \
--minify \
--baseURL "${{ steps.pages.outputs.base_url }}/" \
--cacheDir "${{ runner.temp }}/hugo_cache"
- name: Cache save
id: cache-save
uses: actions/cache/save@v4
with:
path: ${{ runner.temp }}/hugo_cache
key: ${{ steps.cache-restore.outputs.cache-primary-key }}
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./public
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
配置 GitHub Pages
- 访问 GitHub 仓库,进入 Settings > Pages
- 在 Source 下拉菜单中选择 GitHub Actions
- 提交并推送代码到 GitHub
GitHub 会自动运行工作流,构建并部署站点。部署完成后,在 Actions 页面可以看到部署状态和站点链接。
自定义域名
要使用自定义域名:
- 在仓库 Settings > Pages > Custom domain 中添加域名
- 在域名服务商处添加 DNS 记录:
- 对于 apex 域名(如
example.com):添加 A 记录指向 GitHub Pages IP - 对于子域名(如
www.example.com):添加 CNAME 记录指向username.github.io
- 对于 apex 域名(如
- 在站点配置中更新
baseURL
baseURL = 'https://example.com/'
简化版工作流
如果你的站点不需要 Dart Sass(不使用 SCSS),可以简化工作流:
name: Build and deploy
on:
push:
branches:
- main
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
env:
HUGO_VERSION: 0.152.2
steps:
- name: Checkout
uses: actions/checkout@v5
with:
submodules: recursive
fetch-depth: 0
- name: Setup Pages
id: pages
uses: actions/configure-pages@v5
- name: Install Hugo
run: |
curl -sLJO "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
tar -xf "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
rm "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
echo "$PWD" >> "${GITHUB_PATH}"
- name: Build
run: hugo --gc --minify --baseURL "${{ steps.pages.outputs.base_url }}/"
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./public
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
Netlify
Netlify 是一个现代化的托管平台,提供持续集成、自动部署、表单处理、Serverless 函数等功能。
准备工作
- 创建 Netlify 账户
- 创建 Hugo 站点并推送到 GitHub、GitLab 或 Bitbucket
部署方式一:通过界面配置
- 登录 Netlify,进入 Sites 页面
- 点击 Add new site > Import an existing project
- 选择代码托管平台(GitHub、GitLab、Bitbucket)
- 授权 Netlify 访问你的仓库
- 选择要部署的仓库
- 配置构建设置:
- Build command:
hugo --gc --minify - Publish directory:
public
- Build command:
- 添加环境变量
HUGO_VERSION,值为 Hugo 版本号 - 点击 Deploy site
部署方式二:使用配置文件
在项目根目录创建 netlify.toml 文件:
基本配置:
[build.environment]
GO_VERSION = "1.24.2"
HUGO_VERSION = "0.148.0"
NODE_VERSION = "22"
TZ = "Asia/Shanghai"
[build]
publish = "public"
command = "git config core.quotepath false && hugo --gc --minify"
包含 Dart Sass 的配置:
[build.environment]
DART_SASS_VERSION = "1.89.2"
GO_VERSION = "1.24.2"
HUGO_VERSION = "0.148.0"
NODE_VERSION = "22"
TZ = "Asia/Shanghai"
[build]
publish = "public"
command = """\
curl -LJO https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \
tar -xf dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \
rm dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz && \
export PATH=/opt/build/repo/dart-sass:$PATH && \
git config core.quotepath false && \
hugo --gc --minify \
"""
Netlify 特性
预览部署:每个 Pull Request 都会生成预览链接,方便审查
表单处理:无需后端即可处理表单提交
<form name="contact" method="POST" data-netlify="true">
<input type="text" name="name">
<input type="email" name="email">
<textarea name="message"></textarea>
<button type="submit">发送</button>
</form>
重定向和重写:在 netlify.toml 中配置:
[[redirects]]
from = "/old-url/"
to = "/new-url/"
status = 301
[[redirects]]
from = "/api/*"
to = "https://api.example.com/:splat"
status = 200
自定义域名和 HTTPS:Netlify 自动为自定义域名配置 Let's Encrypt 证书
Serverless 函数:在 netlify/functions/ 目录下创建函数
// netlify/functions/hello.js
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello World' })
}
}
环境变量管理
在 Netlify 界面或配置文件中设置环境变量:
[context.production.environment]
HUGO_ENV = "production"
[context.deploy-preview.environment]
HUGO_ENV = "staging"
在模板中使用:
{{ if eq (os.Getenv "HUGO_ENV") "production" }}
<!-- 生产环境代码 -->
{{ end }}
Cloudflare Pages
Cloudflare Pages 提供全球 CDN 加速、无限带宽、自动 HTTPS 等特性。
准备工作
- 创建 Cloudflare 账户
- 将 Hugo 站点推送到 GitHub 或 GitLab
创建配置文件
wrangler.toml:
name = "my-hugo-site"
compatibility_date = "2025-07-31"
[build]
command = "chmod a+x build.sh && ./build.sh"
[assets]
directory = "./public"
not_found_handling = "404-page"
build.sh:
#!/usr/bin/env bash
main() {
DART_SASS_VERSION=1.93.2
GO_VERSION=1.25.3
HUGO_VERSION=0.152.2
NODE_VERSION=22.20.0
export TZ=Asia/Shanghai
# Install Dart Sass
curl -sLJO "https://github.com/sass/dart-sass/releases/download/${DART_SASS_VERSION}/dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz"
tar -C "${HOME}/.local" -xf "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz"
rm "dart-sass-${DART_SASS_VERSION}-linux-x64.tar.gz"
export PATH="${HOME}/.local/dart-sass:${PATH}"
# Install Go
curl -sLJO "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz"
tar -C "${HOME}/.local" -xf "go${GO_VERSION}.linux-amd64.tar.gz"
rm "go${GO_VERSION}.linux-amd64.tar.gz"
export PATH="${HOME}/.local/go/bin:${PATH}"
# Install Hugo
curl -sLJO "https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
mkdir "${HOME}/.local/hugo"
tar -C "${HOME}/.local/hugo" -xf "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
rm "hugo_extended_${HUGO_VERSION}_linux-amd64.tar.gz"
export PATH="${HOME}/.local/hugo:${PATH}"
# Install Node.js
curl -sLJO "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz"
tar -C "${HOME}/.local" -xf "node-v${NODE_VERSION}-linux-x64.tar.xz"
rm "node-v${NODE_VERSION}-linux-x64.tar.xz"
export PATH="${HOME}/.local/node-v${NODE_VERSION}-linux-x64/bin:${PATH}"
# Configure Git
git config core.quotepath false
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
git fetch --unshallow
fi
# Build the site
hugo --gc --minify
}
set -euo pipefail
main "$@"
部署步骤
- 将配置文件提交到仓库
- 登录 Cloudflare Dashboard
- 点击 Add > Workers
- 选择 Import a repository
- 连接 GitHub 或 GitLab 账户
- 选择要部署的仓库
- 设置项目名称,点击 Create and deploy
Cloudflare Pages 优势
- 全球 CDN:利用 Cloudflare 的全球网络加速访问
- 无限带宽:没有带宽限制
- 自动 HTTPS:免费 SSL 证书
- 预览部署:每个 Pull Request 自动生成预览
- Workers 集成:可以添加 Serverless 功能
使用 Cloudflare Functions
在 functions/ 目录下创建函数:
// functions/api/hello.js
export async function onRequest(context) {
return new Response(JSON.stringify({ message: 'Hello World' }), {
headers: { 'Content-Type': 'application/json' }
});
}
Vercel
Vercel 是一个专注于前端部署的平台,提供极速部署体验。
部署方式
方式一:通过界面部署
- 登录 Vercel
- 点击 Add New > Project
- 导入 GitHub 仓库
- Vercel 会自动检测 Hugo 项目
- 点击 Deploy
方式二:通过 CLI 部署
# 安装 Vercel CLI
npm i -g vercel
# 部署
vercel
配置文件
创建 vercel.json 文件进行自定义配置:
{
"build": {
"env": {
"HUGO_VERSION": "0.148.0"
}
},
"outputDirectory": "public"
}
Vercel 特性
- 自动预览:每个分支都有独立预览链接
- 边缘函数:支持 Edge Functions
- 分析功能:内置性能分析
- 多环境:支持 Preview 和 Production 环境
Render
Render 是一个简单易用的云平台,支持静态站点、Web 服务和数据库。
部署步骤
- 登录 Render
- 点击 New > Static Site
- 连接 GitHub 或 GitLab 仓库
- 配置构建设置:
- Build Command:
hugo --gc --minify - Publish Directory:
public
- Build Command:
- 添加环境变量:
HUGO_VERSION: Hugo 版本号
- 点击 Create Static Site
render.yaml 配置
创建 render.yaml 文件:
services:
- type: static
name: my-hugo-site
buildCommand: hugo --gc --minify
publishDirectory: public
envVars:
- key: HUGO_VERSION
value: 0.148.0
Hugo 内置部署
Hugo Extended/Deploy 版本内置了部署命令,可以直接部署到云存储。
安装 Hugo Deploy 版本
从 Hugo Releases 下载 hugo_extended_*_linux-amd64.deb 或带有 deploy 的版本。
配置部署目标
在 hugo.toml 中配置:
AWS S3:
[deployment]
order = [".png$", ".jpg$", ".gif$", ".svg$"]
[[deployment.targets]]
name = "aws-s3"
URL = "s3://my-bucket?region=us-east-1"
cloudFrontDistributionID = "EABCDEF123456"
Google Cloud Storage:
[[deployment.targets]]
name = "gcs"
URL = "gcs://my-bucket"
Azure Blob Storage:
[[deployment.targets]]
name = "azure"
URL = "azblob://my-container"
部署命令
# 部署到配置的目标
hugo deploy
# 部署到特定目标
hugo deploy --target aws-s3
# 干运行(查看将要执行的操作)
hugo deploy --dryRun
# 强制上传所有文件
hugo deploy --force
匹配规则
配置哪些文件优先上传:
[deployment]
order = [".png$", ".jpg$", ".gif$", ".svg$"]
匹配规则的文件会被优先上传,确保大文件在 HTML 之前就位。
rsync 部署
rsync 是传统的文件同步工具,适合部署到自有服务器。
基本命令
rsync -avz --delete public/ user@server:/var/www/site/
参数说明:
-a: 归档模式,保持权限和时间戳-v: 显示详细信息-z: 压缩传输--delete: 删除目标目录中不存在于源目录的文件
创建部署脚本
deploy.sh:
#!/bin/bash
echo "Building site..."
hugo --gc --minify
echo "Deploying to server..."
rsync -avz --delete public/ [email protected]:/var/www/mysite/
echo "Deployment complete!"
使用 SSH 密钥
为避免每次输入密码,配置 SSH 密钥认证:
# 生成密钥对
ssh-keygen -t ed25519 -C "deploy"
# 将公钥复制到服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server
# 测试连接
ssh user@server
配置忽略文件
创建 rsync-exclude.txt:
.DS_Store
.git
.gitignore
node_modules
使用:
rsync -avz --delete --exclude-from=rsync-exclude.txt public/ user@server:/var/www/site/
rclone 部署
rclone 支持多种云存储服务,比 rsync 更灵活。
安装 rclone
# macOS
brew install rclone
# Windows (Scoop)
scoop install rclone
# Linux
curl https://rclone.org/install.sh | sudo bash
配置远程存储
# 交互式配置
rclone config
按提示选择存储类型并配置认证信息。
部署命令
# 同步到 Google Drive
rclone sync public/ remote:mysite
# 同步到 S3
rclone sync public/ s3:my-bucket
# 同步到 Azure Blob
rclone sync public/ azure:my-container
部署脚本
#!/bin/bash
echo "Building site..."
hugo --gc --minify
echo "Deploying with rclone..."
rclone sync public/ remote:mysite --progress
echo "Deployment complete!"
Firebase Hosting
Firebase Hosting 是 Google 提供的静态网站托管服务,适合需要移动应用集成的项目。
安装 Firebase CLI
npm install -g firebase-tools
初始化项目
firebase login
firebase init hosting
配置选项:
- public directory:
public - single-page app: No
- GitHub Actions: Yes(可选)
部署命令
# 手动部署
firebase deploy
# 只部署 hosting
firebase deploy --only hosting
# 部署到特定渠道
firebase hosting:channel:deploy preview
firebase.json 配置
{
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "**/*.@(jpg|jpeg|gif|png|svg|webp|js|css|eot|otf|ttf|ttc|woff|woff2|font.css)",
"headers": [
{
"key": "Cache-Control",
"value": "max-age=604800"
}
]
}
]
}
}
部署最佳实践
1. 环境变量管理
区分不同环境的配置:
# config/production/config.toml
baseURL = 'https://example.com/'
# config/staging/config.toml
baseURL = 'https://staging.example.com/'
构建时指定环境:
hugo --environment production
2. 缓存策略
配置缓存加速构建:
[caches]
[caches.assets]
dir = ':resourceDir/_gen'
maxAge = -1
[caches.images]
dir = ':resourceDir/_gen'
maxAge = -1
[caches.getcsv]
dir = ':cacheDir/:project'
maxAge = '12h'
[caches.getjson]
dir = ':cacheDir/:project'
maxAge = '12h'
3. 版本锁定
在配置文件中明确版本依赖:
[module]
[module.hugoVersion]
extended = true
min = '0.120.0'
4. 构建优化
使用构建优化选项:
hugo --gc --minify
--gc: 清理未使用的资源--minify: 压缩输出文件
5. CI/CD 配置
使用 GitHub Actions 缓存加速构建:
- name: Cache Hugo resources
uses: actions/cache@v4
with:
path: |
~/.cache/hugo_cache
resources
key: ${{ runner.os }}-hugo-${{ hashFiles('**/*.md') }}
restore-keys: |
${{ runner.os }}-hugo-
6. 部署前检查
创建部署前检查脚本:
#!/bin/bash
echo "Running pre-deployment checks..."
# 检查构建是否成功
if ! hugo; then
echo "Build failed!"
exit 1
fi
# 检查死链接
if ! hugo --templateMetrics; then
echo "Template check failed!"
exit 1
fi
# 检查 HTML 有效性
if command -v htmlproofer &> /dev/null; then
htmlproofer public --disable-external
fi
echo "All checks passed!"
7. 回滚策略
保持部署历史以便回滚:
- GitHub Pages:可以通过 Actions 重新运行之前的提交
- Netlify:支持一键回滚到之前版本
- Vercel:支持即时回滚
8. 监控和告警
配置部署状态通知:
GitHub Actions Slack 通知:
- name: Notify on success
if: success()
uses: rtCamp/action-slack-notify@v2
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
SLACK_MESSAGE: 'Site deployed successfully!'
- name: Notify on failure
if: failure()
uses: rtCamp/action-slack-notify@v2
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
SLACK_MESSAGE: 'Deployment failed!'
SLACK_COLOR: 'danger'
部署平台对比
| 平台 | 免费额度 | 自定义域名 | HTTPS | CDN | 预览部署 | 构建时间 |
|---|---|---|---|---|---|---|
| GitHub Pages | 无限制 | ✅ | ✅ | ❌ | ✅ | 10分钟 |
| Netlify | 100GB/月 | ✅ | ✅ | ✅ | ✅ | 15分钟 |
| Cloudflare Pages | 无限制 | ✅ | ✅ | ✅ | ✅ | 20分钟 |
| Vercel | 100GB/月 | ✅ | ✅ | ✅ | ✅ | 10分钟 |
| Render | 100GB/月 | ✅ | ✅ | ✅ | ✅ | 15分钟 |
| Firebase | 10GB/月 | ✅ | ✅ | ✅ | ✅ | 15分钟 |
小结
本章介绍了 Hugo 网站的各种部署方式:
托管平台:
- GitHub Pages:免费、与 GitHub 集成
- Netlify:功能丰富、支持表单和函数
- Cloudflare Pages:全球 CDN、无限带宽
- Vercel:极速部署体验
- Render:简单易用
其他方式:
- Hugo 内置部署:直接部署到云存储
- rsync:适合自有服务器
- rclone:支持多种云存储
- Firebase:Google 生态集成
选择建议:
- 个人博客/项目文档 → GitHub Pages
- 需要表单处理 → Netlify
- 需要全球加速 → Cloudflare Pages
- 需要与 Google 服务集成 → Firebase
- 自有服务器 → rsync/rclone
根据项目需求和预算选择最适合的部署方式。