跳至內容

headers (標頭)

標頭允許您在指定路徑的傳入請求的回應上設定自訂 HTTP 標頭。

要設定自訂 HTTP 標頭,您可以在 `next.config.js` 中使用 `headers` 鍵。

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/about',
        headers: [
          {
            key: 'x-custom-header',
            value: 'my custom header value',
          },
          {
            key: 'x-another-custom-header',
            value: 'my other custom header value',
          },
        ],
      },
    ]
  },
}

`headers` 是一個非同步函式,它預期返回一個陣列,其中包含具有 `source` 和 `headers` 屬性的物件。

  • `source` 是傳入請求的路徑模式。
  • headers 是一個回應標頭物件陣列,具有 keyvalue 屬性。
  • basePathfalseundefined - 若為 false,則 basePath 不會被包含在比對中,僅能用於外部重寫。
  • localefalseundefined - 語系是否不應包含在比對中。
  • has 是一個 has 物件 陣列,具有 typekeyvalue 屬性。
  • missing 是一個 missing 物件 陣列,具有 typekeyvalue 屬性。

標頭會在檔案系統(包含頁面和 /public 檔案)之前檢查。

標頭覆寫行為

如果兩個標頭符合相同路徑並設定相同的標頭鍵,則最後一個標頭鍵將會覆寫第一個。使用以下標頭,路徑 /hello 將導致標頭 x-helloworld,因為最後設定的標頭值為 world

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: 'x-hello',
            value: 'there',
          },
        ],
      },
      {
        source: '/hello',
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
    ]
  },
}

路徑比對

允許路徑比對,例如 /blog/:slug 將會符合 /blog/hello-world(不支援巢狀路徑)

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/blog/:slug',
        headers: [
          {
            key: 'x-slug',
            value: ':slug', // Matched parameters can be used in the value
          },
          {
            key: 'x-slug-:slug', // Matched parameters can be used in the key
            value: 'my other custom header value',
          },
        ],
      },
    ]
  },
}

萬用字元路徑比對
next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/blog/:slug*',
        headers: [
          {
            key: 'x-slug',
            value: ':slug*', // Matched parameters can be used in the value
          },
          {
            key: 'x-slug-:slug*', // Matched parameters can be used in the key
            value: 'my other custom header value',
          },
        ],
      },
    ]
  },
}

正規表示式路徑比對
next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/blog/:post(\\d{1,})',
        headers: [
          {
            key: 'x-post',
            value: ':post',
          },
        ],
      },
    ]
  },
}

以下字元 (){}:*+? 是用於正規表示式路徑比對,因此當在 source 中使用非特殊值時,必須在其前面加上 \\ 來進行跳脫。

next.config.js
module.exports = {
  async headers() {
    return [
      {
        // this will match `/english(default)/something` being requested
        source: '/english\\(default\\)/:slug',
        headers: [
          {
            key: 'x-header',
            value: 'value',
          },
        ],
      },
    ]
  },
}

支援 i18n 的標頭

當將標頭與 i18n 支援搭配使用時,每個 source 都會自動加上前綴來處理設定的 locales,除非您在標頭中加入 locale: false。如果使用 locale: false,您必須在 source 前面加上地區設定前綴,才能正確匹配。

next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },
 
  async headers() {
    return [
      {
        source: '/with-locale', // automatically handles all locales
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // does not handle locales automatically since locale: false is set
        source: '/nl/with-locale-manual',
        locale: false,
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // this matches '/' since `en` is the defaultLocale
        source: '/en',
        locale: false,
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // this gets converted to /(en|fr|de)/(.*) so will not match the top-level
        // `/` or `/fr` routes like /:path* would
        source: '/(.*)',
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
    ]
  },
}

快取控制 靜態圖片導入。您無法在 next.config.js 中為這些資源設定 Cache-Control 標頭。

但是,您可以為其他回應或資料設定 Cache-Control 標頭。

深入瞭解應用程式路由器的 快取

選項 CORS

跨來源資源共用 (CORS) 是一種安全功能,可讓您控制哪些網站可以存取您的資源。您可以設定 Access-Control-Allow-Origin 標頭,允許特定來源存取您的資源。路由處理器.

async headers() {
    return [
      {
        source: "/api/:path*",
        headers: [
          {
            key: "Access-Control-Allow-Origin",
            value: "*", // Set your origin
          },
          {
            key: "Access-Control-Allow-Methods",
            value: "GET, POST, PUT, DELETE, OPTIONS",
          },
          {
            key: "Access-Control-Allow-Headers",
            value: "Content-Type, Authorization",
          },
        ],
      },
    ];
  },

X-DNS-Prefetch-Control

此標頭 控制 DNS 預提取,允許瀏覽器主動對外部連結、圖片、CSS、JavaScript 等執行網域名稱解析。此預提取在背景執行,因此當需要參考的項目時,DNS 更可能已被解析。這減少了使用者點擊連結時的延遲。

{
  key: 'X-DNS-Prefetch-Control',
  value: 'on'
}

Strict-Transport-Security

此標頭 通知瀏覽器應僅使用 HTTPS 存取,而不是使用 HTTP。使用以下設定,所有目前和未來的子網域都將使用 HTTPS,max-age 為 2 年。這會封鎖只能透過 HTTP 提供的頁面或子網域的存取。

如果您部署到 Vercel,則不需要此標頭,因為它會自動添加到所有部署中,除非您在 next.config.js 中宣告 headers

{
  key: 'Strict-Transport-Security',
  value: 'max-age=63072000; includeSubDomains; preload'
}

X-Frame-Options

此標頭 指示是否允許網站顯示在 iframe 中。這可以防止點擊劫持攻擊。

此標頭已被 CSP 的 frame-ancestors 選項取代,現代瀏覽器對其有更好的支援(設定細節請參閱內容安全政策)。

{
  key: 'X-Frame-Options',
  value: 'SAMEORIGIN'
}

Permissions-Policy

此標頭 允許您控制瀏覽器中可使用的功能和 API。它以前稱為 Feature-Policy

{
  key: 'Permissions-Policy',
  value: 'camera=(), microphone=(), geolocation=(), browsing-topics=()'
}

X-Content-Type-Options

此標頭 可防止瀏覽器在未明確設定 Content-Type 標頭的情況下嘗試猜測內容類型。這可以防止允許使用者上傳和分享檔案的網站遭受 XSS 攻擊。

舉例來說,使用者嘗試下載圖片,但伺服器卻以不同的 Content-Type(例如可執行檔,這可能具有惡意)來處理它。這個標頭也適用於下載瀏覽器擴充功能。此標頭唯一有效的數值是 nosniff

{
  key: 'X-Content-Type-Options',
  value: 'nosniff'
}

Referrer-Policy

這個標頭 控制瀏覽器從目前網站(來源)導航到另一個網站時包含多少資訊。

{
  key: 'Referrer-Policy',
  value: 'origin-when-cross-origin'
}

Content-Security-Policy

深入瞭解如何將內容安全策略新增至您的應用程式。

版本歷史記錄

版本變更
v13.3.0新增 missing
v10.2.0新增 has
v9.5.0新增標頭。