紀錄工作經驗、相關知識,解決技術相關問題。

Next

Next.js robots.txt 用法:靜態檔、robots.ts 動態產生、多 user agent 規則與 sitemap 設定

Next.js robots.txt 用法:靜態檔、robots.ts 動態產生、多 user agent 規則與 sitemap 設定 特色圖片

Next.js robots.txt 是 App Router 的檔案慣例:在 app 資料夾根層放一個 robots.txt,或寫一個 robots.ts 回傳 MetadataRoute.Robots 物件,Next.js 就會在 /robots.txt 提供這個檔案,告訴搜尋引擎爬蟲哪些網址可以檢索。本文以 Next.js 16(範例在 16.4.3 執行)說明靜態檔、robots.ts 的型別與每個欄位的輸出、針對不同爬蟲設定規則、Allow 與 Disallow 的比對順序,以及依環境或網域產生不同內容的寫法。其他 metadata 檔(favicon、icon、manifest、opengraph-image、sitemap)的整體介紹見 Next.js Metadata Files 用法。

靜態 robots.txt:放在 app 根層

規則固定不變時,直接在 app/ 根層放 robots.txt:

app/
├─ robots.txt
├─ layout.tsx
└─ page.tsx
User-Agent: *
Allow: /
Disallow: /private/

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

next build 的路由清單會出現 ○ /robots.txt(建置時產生的靜態內容)。next start 後請求 /robots.txt 的回應標頭與內容:

HTTP/1.1 200 OK
cache-control: public, max-age=0, must-revalidate
content-type: text/plain

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

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

位置只能是 app/ 根層。把 robots.txt 放進子資料夾(例如 app/blog/robots.txt),建置不會報錯,但 /blog/robots.txt 回 404,Next.js 不會把它當成 metadata 檔。這和 robots.txt 規範本身一致:Google 只讀網站主機根目錄的 /robots.txt,不會去子目錄找;規則也只套用到檔案所在的通訊協定、主機與連接埠,https://example.com/robots.txt 管不到 https://m.example.com/ 或 http://example.com/。

以前常把 robots.txt 放在 public 資料夾,App Router 官方建議改用 app/ 裡的 metadata 檔案慣例。兩邊同時放會發生什麼事,見下方「robots.txt 衝突」一節。

robots.ts:用 MetadataRoute.Robots 產生

需要用程式決定內容時(例如依環境變數切換),在 app/ 根層建立 robots.ts(或 robots.js),預設匯出一個回傳 Robots 物件的函式:

// 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',
  }
}

/robots.txt 的輸出和上面的靜態檔完全相同:

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

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

robots.ts 是特殊的 Route Handler,預設會快取:函式沒有用到 headers() 這類 Request-time API 或 dynamic 設定時,next build 一樣顯示 ○ /robots.txt,內容在建置時就決定好。

Robots 型別與輸出對照

MetadataRoute.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
}

各欄位對應到 robots.txt 的哪一行:

欄位輸出說明
rules.userAgentUser-Agent:陣列時每個值一行
rules.allowAllow:陣列時每個值一行
rules.disallowDisallow:陣列時每個值一行
rules.crawlDelayCrawl-delay:Google 不支援,見下方說明
rules.other鍵名原樣輸出Next.js 16.3.0 新增,非標準指令用
sitemapSitemap:放在檔案最後,陣列時每個網址一行
hostHost:放在 Sitemap: 之前

rules 有兩種寫法,userAgent 的規定不同:

  • 單一物件:userAgent 可以省略,省略時輸出 User-Agent: *。
  • 陣列:每一項都必須有 userAgent,少寫時 next build 在型別檢查階段失敗:
app/robots.ts(6,7): error TS2322: Type '{ allow: string; disallow: string; }' is not assignable to type 'RobotsRuleBase & { userAgent: string | string[]; }'.
  Property 'userAgent' is missing in type '{ allow: string; disallow: string; }' but required in type '{ userAgent: string | string[]; }'.
Failed to type check.

針對不同爬蟲設定規則:rules 陣列

rules 傳入陣列,就能替不同爬蟲寫不同規則。下面的例子讓 Googlebot 多擋站內搜尋結果頁,並禁止 GPTBot 與 CCBot 檢索整個網站:

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

export default function robots(): MetadataRoute.Robots {
  return {
    rules: [
      {
        userAgent: 'Googlebot',
        allow: ['/'],
        disallow: ['/private/', '/search'],
      },
      {
        userAgent: ['GPTBot', 'CCBot'],
        disallow: '/',
      },
      {
        userAgent: '*',
        allow: '/',
        disallow: '/private/',
      },
    ],
    sitemap: [
      'https://www.example.com/sitemap.xml',
      'https://www.example.com/blog/sitemap.xml',
    ],
  }
}

輸出:

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

User-Agent: GPTBot
User-Agent: CCBot
Disallow: /

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

Sitemap: https://www.example.com/sitemap.xml
Sitemap: https://www.example.com/blog/sitemap.xml

幾個重點:

  • userAgent 給陣列時,Next.js 16.4.3 輸出的是連續幾行 User-Agent: 再接規則(官方文件的輸出範例把它們分成各自一組)。依 Google 的解讀,連續的 User-agent 行屬於同一個群組,兩種寫法對爬蟲的意思相同。
  • 每個爬蟲只會套用一個群組:最明確符合它名稱的那一組,檔案裡的順序不影響結果。指定爬蟲的群組不會和 * 群組合併,所以上面 Googlebot 那組要自己再寫一次 Disallow: /private/,不會從 * 繼承。
  • User-Agent: * 涵蓋所有爬蟲,但 Google 的 AdsBot 系列例外,要擋 AdsBot 必須明確寫出它的名稱。
  • GPTBot 是 OpenAI 用來收集生成式 AI 模型訓練資料的爬蟲,禁止它表示網站內容不應用於訓練;OpenAI 的搜尋用爬蟲 OAI-SearchBot 要另外設定。CCBot 是 Common Crawl 的爬蟲,官方提供的封鎖寫法就是 User-agent: CCBot 加 Disallow: /。
  • robots.txt 只是請求,爬蟲是否遵守由爬蟲自己決定。真正不想公開的內容,要用密碼保護或其他存取控制。

Allow 與 Disallow 的比對規則

同一個群組裡有多條規則都符合某個網址時,RFC 9309 規定採用最明確的那一條,也就是路徑比對到最多字元的規則;Allow 與 Disallow 完全一樣長時,應該採用 Allow。Google 的做法相同:依規則路徑長度選最明確的規則,互相衝突(含萬用字元)時採用限制較少的那條。

網址規則套用結果
/pageAllow: /p、Disallow: /允許,/p 較長、較明確
/folder/pageAllow: /folder、Disallow: /folder允許,衝突時取限制較少的
/page.htmAllow: /page、Disallow: /*.htm禁止,/*.htm 較長
/Allow: /$、Disallow: /允許,/$ 較明確
/page.htmAllow: /$、Disallow: /禁止,/$ 只符合首頁

寫路徑時要注意:

  • 路徑必須以 / 開頭,且區分大小寫:Disallow: /file.asp 擋得到 /file.asp,擋不到 /FILE.asp。
  • Disallow: /fish 是前綴比對,會擋到 /fish.html、/fishheads、/fish/salmon.html;只想擋資料夾就寫 /fish/。
  • Google、Bing 等主要搜尋引擎支援兩種萬用字元:* 代表 0 個以上任意字元,$ 代表網址結尾。例如 Disallow: /*.php$ 只擋結尾是 .php 的網址,/filename.php?parameters 不受影響。
  • 欄位名稱(User-agent、Disallow)不分大小寫,Next.js 輸出的 User-Agent 和 Google 範例的 User-agent 意思相同。

sitemap、host、crawlDelay 與 other 欄位

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

export default function robots(): MetadataRoute.Robots {
  return {
    rules: [
      {
        userAgent: '*',
        allow: '/',
        disallow: '/admin/',
        crawlDelay: 10,
      },
      {
        userAgent: 'SeznamBot',
        allow: '/',
        other: {
          'Request-Rate': '10/1m',
        },
      },
    ],
    host: 'https://www.example.com',
    sitemap: 'https://www.example.com/sitemap.xml',
  }
}

輸出:

User-Agent: *
Allow: /
Disallow: /admin/
Crawl-delay: 10

User-Agent: SeznamBot
Allow: /
Request-Rate: 10/1m

Host: https://www.example.com
Sitemap: https://www.example.com/sitemap.xml
  • sitemap:Google 要求是含通訊協定與主機的完整網址,可以列多個,也可以指向其他主機。Sitemap 不屬於任何 user agent 群組,所以 Next.js 把它放在檔案最後。Next.js 不會自動幫你填 sitemap 網址,有 app/sitemap.ts 時也要自己寫進 sitemap 欄位。
  • crawlDelay:輸出 Crawl-delay:。Google 只支援 user-agent、allow、disallow、sitemap 四個欄位,crawl-delay 會被忽略;其他搜尋引擎是否採用,要查各自的文件。
  • host:輸出 Host:,同樣不在 Google 支援的欄位裡。
  • other:Next.js 16.3.0 新增,用來輸出不在標準裡的指令,例如 Seznam 的 Request-Rate 或 Yandex 的 Clean-param。鍵名保留原本的大小寫,值是陣列時每項各輸出一行({ 'X-Example': ['a', 'b'] } 會輸出 X-Example: a、X-Example: b 兩行),都放在該條規則的 User-Agent 群組裡。Next.js 不檢查指令名稱和值,語法要照目標搜尋引擎的文件寫。

依環境輸出不同規則:測試站禁止檢索

部署到測試站或預覽站時,通常不希望被搜尋引擎檢索。用環境變數切換:

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

const isProduction = process.env.APP_ENV === 'production'

export default function robots(): MetadataRoute.Robots {
  if (!isProduction) {
    // 測試站、預覽站:禁止所有爬蟲檢索
    return {
      rules: { disallow: '/' },
    }
  }

  return {
    rules: { userAgent: '*', allow: '/', disallow: '/admin/' },
    sitemap: 'https://www.example.com/sitemap.xml',
  }
}

沒有設定 APP_ENV 時建置的輸出(單一物件省略 userAgent,輸出 *):

User-Agent: *
Disallow: /

APP_ENV=production 時建置的輸出:

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

Sitemap: https://www.example.com/sitemap.xml

這個 robots.ts 沒有用到 Request-time API,路由清單是 ○ /robots.txt,內容在 next build 時就固定了。用 APP_ENV=production 建置之後,next start 時沒帶這個環境變數,/robots.txt 仍然是正式站的內容。所以環境變數要在建置時設定正確,測試站與正式站要分開建置。

讀取請求標頭:一套程式多個網域

同一份程式部署在多個網域、每個網域的 sitemap 網址不同時,可以在 robots.ts 讀 Host 標頭:

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

export default async function robots(): Promise<MetadataRoute.Robots> {
  const host = (await headers()).get('host') ?? 'www.example.com'

  return {
    rules: { userAgent: '*', allow: '/', disallow: '/admin/' },
    sitemap: `https://${host}/sitemap.xml`,
  }
}

用了 headers() 之後,next build 的路由清單變成 ƒ /robots.txt,每次請求才產生內容。以 Host: shop.example.com 請求時的輸出:

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

Sitemap: https://shop.example.com/sitemap.xml

換成 Host: blog.example.com,最後一行就變成 Sitemap: https://blog.example.com/sitemap.xml。Host 標頭由請求端決定,正式環境要確認反向代理或平台傳進來的值,或改成比對允許的網域清單,不要直接信任任意值。

robots.txt 衝突:robots.ts、public/robots.txt 同時存在

/robots.txt 只能有一個來源,Next.js 16.4.3 遇到重複時的行為:

同時存在next devnext build + next start
app/robots.txt 與 app/robots.ts不報錯,回 robots.txt 的內容建置成功、不報錯,回 robots.txt 的內容
public/robots.txt 與 app/robots.ts回 500,終端顯示下方錯誤建置成功、不報錯,回 public/robots.txt 的內容

public/robots.txt 與 app/robots.ts 同時存在時,next dev 的錯誤訊息:

⨯ A conflicting public file and page file was found for path /robots.txt https://nextjs.org/docs/messages/conflicting-public-file-page
 GET /robots.txt 500

官方說明 public 檔案和頁面檔案同路徑是不支援的寫法,要刪掉或改名其中一個。正式環境建置不會出現這個錯誤,robots.ts 寫得再多也不會生效,容易誤以為設定成功。從 Pages Router 升級或照舊教學寫過 public/robots.txt 的專案,改用 robots.ts 時記得刪掉 public/robots.txt。

robots.txt 不能阻止網頁被索引

robots.txt 管的是檢索,不是索引。Google 官方說明 robots.txt 主要用來管理爬蟲對網站的請求量,不是讓網頁不出現在 Google 的方法:被 Disallow 的網址如果有其他網站連結,仍然可能出現在搜尋結果,只是沒有摘要說明。

要讓頁面不被索引,用 noindex。在 Next.js 可以用 metadata 的 robots 欄位:

// app/admin/layout.tsx
import type { Metadata } from 'next'

export const metadata: Metadata = {
  robots: { index: false, follow: false },
}

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  return children
}

/admin 底下的頁面會輸出:

<meta name="robots" content="noindex, nofollow"/>

要注意兩者不能同時用在同一個網址:Google 規定 noindex 要生效,頁面不能被 robots.txt 封鎖,否則爬蟲根本讀不到頁面上的 noindex。想讓已收錄的頁面從搜尋結果消失,要先讓爬蟲能檢索它、看到 noindex,不要同時在 robots.ts 寫 Disallow。

部署後檢查與注意事項

  • Google 的快取:Google 通常會快取 robots.txt 最多 24 小時,改完不會立刻生效。
  • 檔案大小:Google 只讀前 500 KiB,超過的內容會被忽略。規則太多時,把要排除的內容集中到同一個資料夾再一次 Disallow。
  • 回應狀態碼:/robots.txt 回 4xx(429 除外)時,Google 視為沒有 robots.txt、整站都可以檢索。用 proxy.ts 做登入檢查或重新導向時,matcher 要排除 /robots.txt,避免爬蟲拿到登入頁或錯誤狀態碼,matcher 寫法見 Next.js proxy.js 用法。
  • 確認內容:部署後直接開 https://你的網域/robots.txt 看輸出,再用 Google Search Console 的 robots.txt 報表確認 Google 讀到的版本。

參考資料與延伸閱讀

發佈留言