{
  "id": "add-a-sitemap-and-robots",
  "type": "playbooks",
  "category": "playbooks",
  "locale": "zh",
  "url": "/zh/playbooks/add-a-sitemap-and-robots",
  "title": "Prompt-to-PR：为网站添加站点地图和robots.txt",
  "description": "为Next.js或Astro项目添加动态XML站点地图和robots.txt的标准操作流程——确保正确的lastmod、优先级以及生产环境SEO的爬取规则。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "Astro",
    "TypeScript"
  ],
  "tags": [
    "seo",
    "nextjs",
    "astro",
    "typescript"
  ],
  "difficulty": "easy",
  "updated": "2026-06-08",
  "markdown": "站点地图和`robots.txt`是智能体最先接触的SEO基础元素，但它们经常出错——`lastmod`格式错误、robots文件中缺少`Sitemap:`指令，或者无意中包含了被屏蔽的页面。本手册将确保它们正确无误。\n\n## 1. 需求\n\n生成一个XML站点地图，覆盖所有公开路由（静态路由以及数据库中的动态内容），以及一个`robots.txt`文件，屏蔽管理后台/API路径，并引用站点地图。此方案适用于Next.js App Router和Astro；请根据你的框架选择正确的方法。\n\n## 2. 首次提示\n\n```txt title=\"First Prompt\"\nAdd a sitemap.xml and robots.txt to this project. Use the correct approach\nfor the framework detected below.\n\n### If Next.js 14+:\n1. Create `src/app/sitemap.ts` using the Next.js `MetadataRoute.Sitemap`\n   return type. Include:\n   - All static routes: /, /pricing, /blog, /about (hardcoded is fine).\n   - All dynamic blog posts: fetch slugs from the DB using the existing\n     query helper, return lastModified from the post's updatedAt field.\n   - Use `process.env.NEXT_PUBLIC_APP_URL` as the base URL.\n   - Correct W3C datetime format for lastModified (ISO 8601).\n2. Create `src/app/robots.ts` using MetadataRoute.Robots.\n   - Allow: all routes.\n   - Disallow: /admin, /api, /dashboard.\n   - Add `sitemap: process.env.NEXT_PUBLIC_APP_URL + \"/sitemap.xml\"`.\n\n### If Astro:\n1. Add `@astrojs/sitemap` integration. In astro.config.ts, add\n   `sitemap({ filter: (page) => !page.includes(\"/admin\") })` and set\n   `site: process.env.SITE_URL`.\n2. Create `public/robots.txt`:\n   User-agent: *\n   Disallow: /admin\n   Disallow: /api\n   Sitemap: <SITE_URL>/sitemap-index.xml\n\nDo not create a custom sitemap endpoint if the integration handles it.\nDo not block / or any public content pages.\n```\n\n## 3. 预期文件变更\n\n```txt\n### Next.js\nsrc/app/sitemap.ts             (new — dynamic MetadataRoute.Sitemap)\nsrc/app/robots.ts              (new — MetadataRoute.Robots)\n\n### Astro\nastro.config.ts                (add sitemap integration + filter)\npublic/robots.txt              (new)\n.env.example                   (SITE_URL added if missing)\n```\n\n## 4. 审查清单\n\n- 基础URL来自环境变量——不要硬编码为`http://localhost:3000`。\n- `lastModified`是JavaScript的`Date`对象（Next.js会将其转换为ISO 8601格式），或者已经是有效的ISO字符串——不能是`\"undefined\"`或缺失。\n- `/admin`、`/api`和`/dashboard`位于Disallow列表中。\n- `robots.txt`中的`Sitemap:`指令使用绝对URL。\n- 动态路由（如博客文章）通过数据库查询包含，而不仅仅是静态路由。\n- 站点地图不包括404、重定向或无索引页面。\n- 运行`bun run build`，然后`curl /sitemap.xml`返回有效的XML（用`xmllint`检查）。\n\n## 5. 测试命令\n\n```bash\nbun run build && bun run start\n# or for Astro:\nbun run build && bun run preview\n\n# Validate sitemap XML\ncurl -s http://localhost:3000/sitemap.xml | xmllint --format - | head -40\n\n# Confirm robots.txt\ncurl http://localhost:3000/robots.txt\n\n# Confirm admin is disallowed and sitemap directive is present\ngrep -E \"Disallow|Sitemap\" <(curl -s http://localhost:3000/robots.txt)\n\n# Google Rich Results / URL Inspection simulation\ncurl -A \"Googlebot\" http://localhost:3000/sitemap.xml -I\n```\n\n## 6. 常见失败原因\n\n- **`lastModified`为`\"undefined\"`**——文章的`updatedAt`字段为空。防范措施：`lastModified: post.updatedAt ?? post.createdAt ?? new Date()`。\n- **站点地图返回404**——`src/app/sitemap.ts`缺失或位于`app`目录之外。\n- **所有路由都被禁止**——智能体错误地添加了`Disallow: /`。确认只屏蔽管理后台/API路径。\n- **`Sitemap:`指令使用相对URL**——Google会忽略它。必须是绝对URL：`https://example.com/sitemap.xml`。\n- **仅包含静态站点地图**——智能体硬编码了博客路径而不是查询数据库。确认站点地图函数是`async`的并获取实际数据。\n\n## 7. 修复提示\n\n```txt title=\"Fix Prompt\"\nThe sitemap.xml at /sitemap.xml includes every blog post with\nlastModified \"undefined\" (rendered as the string).\n\nFix in src/app/sitemap.ts:\n  const posts = await getBlogPosts();\n  return posts.map((post) => ({\n    url: `${BASE_URL}/blog/${post.slug}`,\n    lastModified: post.updatedAt ?? post.createdAt ?? new Date(),\n    changeFrequency: \"weekly\",\n    priority: 0.8,\n  }));\n\nEnsure getBlogPosts() returns rows that include updatedAt and createdAt.\n```\n\n## 8. PR描述\n\n```md title=\"PR description\"\n## SEO: Add dynamic sitemap.xml and robots.txt\n\n**Next.js**: `src/app/sitemap.ts` + `src/app/robots.ts` using built-in\n`MetadataRoute` types. Sitemap includes static routes + all published blog\nposts with correct `lastModified` timestamps from the DB.\n\n**robots.txt** disallows `/admin`, `/api`, `/dashboard`; includes absolute\n`Sitemap:` directive pointing to the generated `/sitemap.xml`.\n\nBase URL read from `NEXT_PUBLIC_APP_URL` — no localhost URLs in production.\n```"
}