从 Hugo 无损迁移到 Astro:URL 路由、SEO 与双主题排版实践

2 分钟阅读

提示: 本文为迁移验证示例文章,用于检验 Hugo Frontmatter 解析、中文阅读时长计算、Shiki 亮暗双主题代码块、表格以及 BlogPosting JSON-LD 输出。当你把原有的 Hugo Markdown 文章复制到 src/content/blog/ 后,可直接删除此文件。

在将静态技术博客从 Hugo 迁移到 Astro 时,最重要的工程目标并不是页面视觉翻新,而是零 SEO 权重损失:确保既有文章、分类页、标签页与 RSS 订阅地址 100% 保持一致。

1. 保留 Hugo URL 结构与 Trailing Slash

通过在 astro.config.mjs 中显式锁定 site 与 trailingSlash,可以避免搜索引擎把 /post/example 与 /post/example/ 视作重复页面:

# 原 Hugo 配置参考
baseURL = "https://smc.im/"
[permalinks]
  post = "/post/:slug/"

对应的 Astro Content Layer ID 映射逻辑如下(优先读取 Frontmatter 中的 slug):

export function resolvePostUrl(slug: string): string {
  const normalized = slug.replace(/^\/+|\/+$/g, "");
  return `/post/${normalized}/`;
}

2. 常见路由映射对照表

页面类型 原 Hugo 路径 Astro 路由文件 SEO 与规范策略
文章归档 /post/ src/pages/post/index.astro 按年份倒序 + 阅读时长
文章详情 /post/<slug>/ src/pages/post/[...slug].astro Canonical + BlogPosting JSON-LD
分类归档 /categories/<name>/ src/pages/categories/[category].astro 兼容大小写与 Unicode slug
标签归档 /tags/<name>/ src/pages/tags/[tag].astro 聚合计数与直达筛选
RSS 订阅 /index.xml src/pages/index.xml.ts 同时兼容 /rss.xml

3. 命令行快速检查

完成文章复制后,可随时使用内联 code 与以下命令触发完整静态构建:

npm run build

构建完成后,检查 dist/sitemap-index.xml 与 dist/index.xml 即可确认所有文章已被完整收录。