跳到主要内容

robots.txt

app 目录的根目录中添加或生成符合 Robots 排除标准robots.txt 文件,以告诉搜索引擎爬虫它们可以访问你网站上的哪些 URL。

静态 robots.txt

app/robots.txt
User-Agent: *
Allow: /
Disallow: /private/

Sitemap: https://acme.com/sitemap.xml

生成 Robots 文件

添加一个返回 Robots 对象robots.jsrobots.ts 文件。

提示robots.js 是特殊的路由处理器,默认会被缓存,除非它使用动态 API动态配置选项。

app/robots.ts
import type { MetadataRoute } from 'next'

export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: '*',
allow: '/',
disallow: '/private/',
},
sitemap: 'https://acme.com/sitemap.xml',
}
}

输出:

User-Agent: *
Allow: /
Disallow: /private/

Sitemap: https://acme.com/sitemap.xml

自定义特定的用户代理

你可以通过向 rules 属性传递用户代理数组来自定义各个搜索引擎机器人如何爬取你的网站。例如:

app/robots.ts
import type { MetadataRoute } from 'next'

export default function robots(): MetadataRoute.Robots {
return {
rules: [
{
userAgent: 'Googlebot',
allow: ['/'],
disallow: '/private/',
},
{
userAgent: ['Applebot', 'Bingbot'],
disallow: ['/'],
},
],
sitemap: 'https://acme.com/sitemap.xml',
}
}

输出:

User-Agent: Googlebot
Allow: /
Disallow: /private/

User-Agent: Applebot
Disallow: /

User-Agent: Bingbot
Disallow: /

Sitemap: https://acme.com/sitemap.xml

Robots 对象

type Robots = {
rules:
| {
userAgent?: string | string[]
allow?: string | string[]
disallow?: string | string[]
crawlDelay?: number
}
| Array<{
userAgent: string | string[]
allow?: string | string[]
disallow?: string | string[]
crawlDelay?: number
}>
sitemap?: string | string[]
host?: string
}

版本历史

版本变更
v13.3.0引入 robots