robots.txt
robots.txt 文件的 API 参考。
在 app 目录的根目录中添加或生成一个符合 Robots Exclusion Standard 的 robots.txt 文件,以告知搜索引擎爬虫它们可以访问你网站上的哪些 URL。
静态 robots.txt
app/robots.txttxt
User-Agent: *
Allow: /
Disallow: /private/
Sitemap: https://acme.com/sitemap.xml
生成 Robots 文件
添加一个 robots.js 或 robots.ts 文件,返回一个 Robots 对象。
须知:
TypeScript
app/robots.tsts
import type { MetadataRoute } from 'next'
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: '*',
allow: '/',
disallow: '/private/',
},
sitemap: 'https://acme.com/sitemap.xml',
}
}
JavaScript
app/robots.jsjs
export default function 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 属性,来自定义各个搜索引擎爬虫抓取你网站的方式。例如:
TypeScript
app/robots.tsts
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',
}
}
JavaScript
app/robots.jsjs
export default function 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 Exclusion Standard 的指令,例如 Request-Rate(Seznam)或 Clean-param(Yandex)。通过规则上的 other 字段传递这些指令。键会保留其大小写,数组值会为每个条目输出一行,作用范围限定在该规则的 User-Agent 块内。
TypeScript
app/robots.tsts
import type { MetadataRoute } from 'next'
export default function robots(): MetadataRoute.Robots {
return {
rules: [
{ userAgent: '*', allow: '/' },
{
userAgent: 'SeznamBot',
allow: '/',
other: {
'Request-Rate': '10/1m',
},
},
],
}
}
JavaScript
app/robots.jsjs
export default function robots() {
return {
rules: [
{ userAgent: '*', allow: '/' },
{
userAgent: 'SeznamBot',
allow: '/',
other: {
'Request-Rate': '10/1m',
},
},
],
}
}
输出:
User-Agent: *
Allow: /
User-Agent: SeznamBot
Allow: /
Request-Rate: 10/1m
须知:
other中的值会原样传递。Next.js 不会验证指令名称或值,因此请参阅目标搜索引擎的文档以了解确切的语法。
Robots 对象
type Robots = {
rules:
| {
userAgent?: string | string[]
allow?: string | string[]
disallow?: string | string[]
crawlDelay?: number
other?: Record<string, string | number | Array<string | number>>
}
| Array<{
userAgent: string | string[]
allow?: string | string[]
disallow?: string | string[]
crawlDelay?: number
other?: Record<string, string | number | Array<string | number>>
}>
sitemap?: string | string[]
host?: string
}
版本历史
| 版本 | 变更 |
|---|---|
v16.3.0 |
新增 other 字段,用于存放非标准的按 agent 指令。 |
v13.3.0 |
引入 robots。 |