添加站点地图和robots.txt的提示词
AI代理提示词:为Next.js或Astro项目动态生成sitemap.xml和正确的robots.txt以改善搜索引擎索引。
CursorClaude CodeCodexWindsurf Next.jsAstroTypeScript
将此提示词提供给您的代理,以添加符合标准的sitemap.xml和robots.txt——处理动态路由、优先级值和最后修改日期,无需使用付费第三方服务。
主提示词
You are working in a Next.js 15 App Router project with TypeScript.The site has static pages (/, /about, /pricing) and dynamic blog posts in `src/content/blog/`.
Task: add sitemap.xml and robots.txt using only Next.js built-in file conventions.
Requirements:- Create `src/app/sitemap.ts` (NOT `.xml`) using the Next.js `MetadataRoute.Sitemap` return type. - Static URLs: `/`, `/about`, `/pricing` with `priority: 1.0` and `changeFrequency: 'monthly'`. - Dynamic URLs: read all MDX files from `src/content/blog/` using `getCollection('blog')` from `astro:content` — wait, this is Next.js, so use `fs` + `gray-matter` to read frontmatter. - For each post, return `{ url, lastModified, changeFrequency: 'weekly', priority: 0.8 }`. - `url` must be an absolute URL using the `NEXT_PUBLIC_SITE_URL` environment variable.- Create `src/app/robots.ts` (NOT `.txt`) using the `MetadataRoute.Robots` return type. - Allow all crawlers for `/*`. - Disallow `/api/*` and `/admin/*` for all crawlers. - Set `sitemap` to the absolute sitemap URL.- Add `NEXT_PUBLIC_SITE_URL=https://example.com` to `.env.example`.- Do NOT install `next-sitemap` or any sitemap package.
Stop and list all files before writing code.实现注意事项
app/目录下的sitemap.ts和robots.ts是Next.js 13.3+的文件约定;它们必须导出一个默认函数,返回类型化的元数据对象——而不是Response或字符串。- 如果构建时
NEXT_PUBLIC_SITE_URL未定义,站点地图将包含相对URL,根据站点地图协议这是无效的——请通过启动检查进行验证。 lastModified应为Date对象,而非字符串;Next.js会将其序列化为ISO 8601格式。
预期文件更改
src/app/sitemap.ts (new)src/app/robots.ts (new)src/lib/blog.ts (new or edited — getAllPosts helper).env.example (edited)验收标准
GET /sitemap.xml返回有效的XML,所有静态和动态URL均为绝对URL。GET /robots.txt包含Disallow: /api/和Sitemap: https://example.com/sitemap.xml。- 添加新的博客文章MDX文件后,执行
bun run build其URL将出现在站点地图中。 - 站点地图在 https://www.xml-sitemaps.com/validate-xml-sitemap.html 验证通过。
测试命令
bun run build && bun run startcurl http://localhost:3000/sitemap.xml | xmllint --format - | head -40curl http://localhost:3000/robots.txt# confirm /api/ is disallowed and sitemap URL is absolutebun run typecheck常见的AI错误
- 创建静态的
public/sitemap.xml文件,而不是使用动态的src/app/sitemap.ts约定。 - 在站点地图中使用相对URL(例如
/blog/my-post)——站点地图需要绝对URL。 - 在提示词明确禁止的情况下安装
next-sitemap。 - 将
robots.txt设置为禁止所有爬虫(Disallow: /),这会导致整个网站被取消索引。
修复提示词
The sitemap contains relative URLs or robots.txt disallows too much. Fix in order:1. In `src/app/sitemap.ts`, construct every URL as: `const base = process.env.NEXT_PUBLIC_SITE_URL ?? 'https://example.com'; url: \`\${base}/blog/\${post.slug}\``2. In `src/app/robots.ts`, verify the rules object: `{ userAgent: '*', allow: '/', disallow: ['/api/', '/admin/'] }`.3. Confirm `sitemap.ts` exports a default async function (not a named export).Show only the corrected diff.