# Prompt-to-PR：为网站添加站点地图和robots.txt

> 为Next.js或Astro项目添加动态XML站点地图和robots.txt的标准操作流程——确保正确的lastmod、优先级以及生产环境SEO的爬取规则。

**Type:** Playbook  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Next.js, Astro, TypeScript  
**Difficulty:** easy  
**Updated:** 2026-06-08

---

站点地图和`robots.txt`是智能体最先接触的SEO基础元素，但它们经常出错——`lastmod`格式错误、robots文件中缺少`Sitemap:`指令，或者无意中包含了被屏蔽的页面。本手册将确保它们正确无误。

## 1. 需求

生成一个XML站点地图，覆盖所有公开路由（静态路由以及数据库中的动态内容），以及一个`robots.txt`文件，屏蔽管理后台/API路径，并引用站点地图。此方案适用于Next.js App Router和Astro；请根据你的框架选择正确的方法。

## 2. 首次提示

```txt title="First Prompt"
Add a sitemap.xml and robots.txt to this project. Use the correct approach
for the framework detected below.

### If Next.js 14+:
1. Create `src/app/sitemap.ts` using the Next.js `MetadataRoute.Sitemap`
   return type. Include:
   - All static routes: /, /pricing, /blog, /about (hardcoded is fine).
   - All dynamic blog posts: fetch slugs from the DB using the existing
     query helper, return lastModified from the post's updatedAt field.
   - Use `process.env.NEXT_PUBLIC_APP_URL` as the base URL.
   - Correct W3C datetime format for lastModified (ISO 8601).
2. Create `src/app/robots.ts` using MetadataRoute.Robots.
   - Allow: all routes.
   - Disallow: /admin, /api, /dashboard.
   - Add `sitemap: process.env.NEXT_PUBLIC_APP_URL + "/sitemap.xml"`.

### If Astro:
1. Add `@astrojs/sitemap` integration. In astro.config.ts, add
   `sitemap({ filter: (page) => !page.includes("/admin") })` and set
   `site: process.env.SITE_URL`.
2. Create `public/robots.txt`:
   User-agent: *
   Disallow: /admin
   Disallow: /api
   Sitemap: <SITE_URL>/sitemap-index.xml

Do not create a custom sitemap endpoint if the integration handles it.
Do not block / or any public content pages.
```

## 3. 预期文件变更

```txt
### Next.js
src/app/sitemap.ts             (new — dynamic MetadataRoute.Sitemap)
src/app/robots.ts              (new — MetadataRoute.Robots)

### Astro
astro.config.ts                (add sitemap integration + filter)
public/robots.txt              (new)
.env.example                   (SITE_URL added if missing)
```

## 4. 审查清单

- 基础URL来自环境变量——不要硬编码为`http://localhost:3000`。
- `lastModified`是JavaScript的`Date`对象（Next.js会将其转换为ISO 8601格式），或者已经是有效的ISO字符串——不能是`"undefined"`或缺失。
- `/admin`、`/api`和`/dashboard`位于Disallow列表中。
- `robots.txt`中的`Sitemap:`指令使用绝对URL。
- 动态路由（如博客文章）通过数据库查询包含，而不仅仅是静态路由。
- 站点地图不包括404、重定向或无索引页面。
- 运行`bun run build`，然后`curl /sitemap.xml`返回有效的XML（用`xmllint`检查）。

## 5. 测试命令

```bash
bun run build && bun run start
# or for Astro:
bun run build && bun run preview

# Validate sitemap XML
curl -s http://localhost:3000/sitemap.xml | xmllint --format - | head -40

# Confirm robots.txt
curl http://localhost:3000/robots.txt

# Confirm admin is disallowed and sitemap directive is present
grep -E "Disallow|Sitemap" <(curl -s http://localhost:3000/robots.txt)

# Google Rich Results / URL Inspection simulation
curl -A "Googlebot" http://localhost:3000/sitemap.xml -I
```

## 6. 常见失败原因

- **`lastModified`为`"undefined"`**——文章的`updatedAt`字段为空。防范措施：`lastModified: post.updatedAt ?? post.createdAt ?? new Date()`。
- **站点地图返回404**——`src/app/sitemap.ts`缺失或位于`app`目录之外。
- **所有路由都被禁止**——智能体错误地添加了`Disallow: /`。确认只屏蔽管理后台/API路径。
- **`Sitemap:`指令使用相对URL**——Google会忽略它。必须是绝对URL：`https://example.com/sitemap.xml`。
- **仅包含静态站点地图**——智能体硬编码了博客路径而不是查询数据库。确认站点地图函数是`async`的并获取实际数据。

## 7. 修复提示

```txt title="Fix Prompt"
The sitemap.xml at /sitemap.xml includes every blog post with
lastModified "undefined" (rendered as the string).

Fix in src/app/sitemap.ts:
  const posts = await getBlogPosts();
  return posts.map((post) => ({
    url: `${BASE_URL}/blog/${post.slug}`,
    lastModified: post.updatedAt ?? post.createdAt ?? new Date(),
    changeFrequency: "weekly",
    priority: 0.8,
  }));

Ensure getBlogPosts() returns rows that include updatedAt and createdAt.
```

## 8. PR描述

```md title="PR description"
## SEO: Add dynamic sitemap.xml and robots.txt

**Next.js**: `src/app/sitemap.ts` + `src/app/robots.ts` using built-in
`MetadataRoute` types. Sitemap includes static routes + all published blog
posts with correct `lastModified` timestamps from the DB.

**robots.txt** disallows `/admin`, `/api`, `/dashboard`; includes absolute
`Sitemap:` directive pointing to the generated `/sitemap.xml`.

Base URL read from `NEXT_PUBLIC_APP_URL` — no localhost URLs in production.
```