跳至主要內容

    X-Robots-Tag

    X-Robots-Tag 是 HTTP 回應標頭,可用於 HTML 或非 HTML(PDF、圖片)來下達 noindex/nofollow 等指令。

    定義

    X-Robots-Tag 是伺服器在回應時附上的 HTTP Header,用法與 meta robots 類似,但更通用:你可以對非 HTML 資源(如 PDF)設定 noindex,也可以用於整個目錄或特定路徑的規則化控制。

    為什麼重要

    • 可控制 PDF/附件等非 HTML 的索引行為
    • 適合在伺服器層用規則批次套用(比逐頁改 HTML 更快)
    • 搭配 Cloudflare/反向代理規則管理索引範圍
    • 統一管理測試/開發環境 — 一條規則即可全站 noindex
    • 可針對特定爬蟲設定不同規則 — 如 googlebot-news: noindex
    • 與 CDN 整合更容易 — 在邊緣節點統一處理,不改原始碼
    • 支援更多指令 — unavailable_after 設定頁面過期時間

    怎麼做(實作重點)

    • 用 noindex 移除不該出現在 SERP 的資源
    • 避免與 robots.txt 衝突:若完全擋 crawl,索引狀態可能不易更新
    • 用工具檢查 HTTP response headers,確認標頭真的有送出
    • 在 Nginx/Apache 用 location 或 FilesMatch 針對路徑/副檔名設定
    • Cloudflare 用 Transform Rules 或 Workers 動態加 header
    • 多個指令可用逗號分隔或多個 X-Robots-Tag header
    • 用 curl -I 或 Chrome DevTools Network 面板驗證 header 有效

    範例

    nginx
    # 所有 PDF 不索引
    location ~* \.pdf$ {
        add_header X-Robots-Tag "noindex, nofollow" always;
    }
    
    # 整個 /admin/ 目錄不索引
    location /admin/ {
        add_header X-Robots-Tag "noindex" always;
    }
    
    # 針對特定爬蟲
    location /news/ {
        add_header X-Robots-Tag "googlebot: noindex" always;
        add_header X-Robots-Tag "bingbot: noindex" always;
    }
    
    # 設定過期時間(UTC 格式)
    location /promotions/ {
        add_header X-Robots-Tag "unavailable_after: 25 Dec 2025 00:00:00 UTC" always;
    }
    typescript
    // Cloudflare Worker - 根據路徑動態加 X-Robots-Tag
    export default {
      async fetch(request: Request): Promise<Response> {
        const url = new URL(request.url);
        const response = await fetch(request);
        
        // 複製 response 以便修改 headers
        const newResponse = new Response(response.body, response);
        
        // 開發/測試環境全站 noindex
        if (url.hostname.includes('staging') || url.hostname.includes('dev')) {
          newResponse.headers.set('X-Robots-Tag', 'noindex, nofollow');
          return newResponse;
        }
        
        // PDF 和附件不索引
        if (url.pathname.match(/\.(pdf|doc|docx|xls|xlsx)$/i)) {
          newResponse.headers.set('X-Robots-Tag', 'noindex');
        }
        
        // 內部搜尋結果不索引
        if (url.pathname.startsWith('/search')) {
          newResponse.headers.set('X-Robots-Tag', 'noindex, follow');
        }
        
        return newResponse;
      },
    };

    相關連結

    常見問題

    關於這個詞彙的常見問答。

    回到詞彙表