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 是一种特殊的路由处理器 (Route Handlers),默认会被缓存,除非它使用了 动态 API动态配置 选项。

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 属性传递用户代理数组,来定制单个搜索引擎爬虫如何抓取您的网站。例如:

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 功能。

On this page