N Next.js 中文
原文 ↗

headers

为你的 Next.js 应用添加自定义 HTTP 标头。

更新于 2026-06-30Next.js 16.4.6

标头允许你为给定路径上的传入请求,在响应中设置自定义 HTTP 标头。

要设置自定义 HTTP 标头,你可以使用 next.config.js 中的 headers 键:

next.config.jsjs
module.exports = {
  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 是一个响应标头对象数组,这些对象具有 key 和 value 属性。
  • basePath:false 或 undefined - 如果为 false,匹配时不会包含 basePath,且仅可用于外部重写。
  • locale:false 或 undefined - 匹配时是否不应包含区域设置。
  • has 是一个 has 对象 数组,包含 type、key 和 value 属性。
  • missing 是一个 missing 对象 数组,包含 type、key 和 value 属性。

系统会先检查标头,再检查文件系统(包括 pages 和 /public 文件)。

标头覆盖行为

如果两个标头匹配同一路径并设置了相同的标头键,则后一个标头键将覆盖前一个。使用下面的标头时,路径 /hello 的标头 x-hello 将为 world,因为最后设置的标头值是 world。

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

路径匹配

支持路径匹配,例如 /blog/:slug 将匹配 /blog/first-post(不匹配嵌套路径):

next.config.jsjs
module.exports = {
  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',
          },
        ],
      },
    ]
  },
}

模式 /blog/:slug 匹配 /blog/first-post 和 /blog/post-1,但不匹配像 /blog/a/b 这样的嵌套路径。模式锚定在开头,/blog/:slug 将不匹配 /archive/blog/first-post。

你可以在参数上使用修饰符:*(零次或多次)、+(一次或多次)、?(零次或一次)。例如,/blog/:slug* 匹配 /blog、/blog/a 和 /blog/a/b/c。

在 path-to-regexp 文档中阅读更多细节。

通配符路径匹配

要匹配通配符路径,你可以在参数后使用 *,例如 /blog/:slug* 将匹配 /blog/a/b/c/d/hello-world:

next.config.jsjs
module.exports = {
  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',
          },
        ],
      },
    ]
  },
}

正则表达式路径匹配

要匹配正则表达式路径,你可以将正则表达式用括号包裹在参数之后,例如 /blog/:slug(\\d{1,}) 将匹配 /blog/123,但不匹配 /blog/abc:

next.config.jsjs
module.exports = {
  headers() {
    return [
      {
        source: '/blog/:post(\\d{1,})',
        headers: [
          {
            key: 'x-post',
            value: ':post',
          },
        ],
      },
    ]
  },
}

以下字符 (、)、{、}、:、*、+、? 用于正则表达式路径匹配,因此当它们在 source 中作为非特殊值使用时,必须通过在其前面添加 \\ 进行转义:

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

标头、Cookie 和查询匹配

要仅在标头、Cookie 或查询值也匹配 has 字段,或不匹配 missing 字段时才应用某个标头,可以使用 has 和 missing。source 以及所有 has 项都必须匹配,并且所有 missing 项都必须不匹配,标头才会被应用。

has 和 missing 项可以包含以下字段:

  • type:String - 必须是 header、cookie、host 或 query 之一。
  • key:String - 所选类型中用于匹配的键。
  • value:String 或 undefined - 要检查的值,如果为 undefined,则任何值都会匹配。可以使用类似正则的字符串来捕获值的特定部分,例如,如果对 first-second 使用值 first-(?<paramName>.*),那么在目标位置就可以通过 :paramName 使用 second。
next.config.jsjs
module.exports = {
  headers() {
    return [
      // if the header `x-add-header` is present,
      // the `x-another-header` header will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-add-header',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: 'hello',
          },
        ],
      },
      // if the header `x-no-header` is not present,
      // the `x-another-header` header will be applied
      {
        source: '/:path*',
        missing: [
          {
            type: 'header',
            key: 'x-no-header',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: 'hello',
          },
        ],
      },
      // if the source, query, and cookie are matched,
      // the `x-authorized` header will be applied
      {
        source: '/specific/:path*',
        has: [
          {
            type: 'query',
            key: 'page',
            // the page value will not be available in the
            // header key/values since value is provided and
            // doesn't use a named capture group e.g. (?<page>home)
            value: 'home',
          },
          {
            type: 'cookie',
            key: 'authorized',
            value: 'true',
          },
        ],
        headers: [
          {
            key: 'x-authorized',
            value: ':authorized',
          },
        ],
      },
      // if the header `x-authorized` is present and
      // contains a matching value, the `x-another-header` will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: ':authorized',
          },
        ],
      },
      // if the host is `example.com`,
      // this header will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'host',
            value: 'example.com',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: ':authorized',
          },
        ],
      },
    ]
  },
}

支持 basePath 的标头

在结合标头使用 basePath 支持时,每个 source 都会自动加上 basePath 前缀,除非你为标头添加 basePath: false:

next.config.jsjs
module.exports = {
  basePath: '/docs',

  headers() {
    return [
      {
        source: '/with-basePath', // becomes /docs/with-basePath
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        source: '/without-basePath', // is not modified since basePath: false is set
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
        basePath: false,
      },
    ]
  },
}

支持 i18n 的标头

在结合标头使用 i18n 支持时,每个 source 都会自动加上前缀以处理所配置的 locales,除非你为标头添加 locale: false。如果使用了 locale: false,则必须为 source 加上语言区域前缀,才能正确匹配。

next.config.jsjs
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },

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

Cache-Control

对于真正不可变的资源,Next.js 会将 public, max-age=31536000, immutable 的 Cache-Control 标头设置为不可覆盖。这些不可变文件的文件名中包含 SHA 哈希,因此可以安全地永久缓存。例如,静态图片导入。对于这些资源,你无法在 next.config.js 中设置 Cache-Control 标头。

不过,你可以为其他响应或数据设置 Cache-Control 标头。

了解有关在 App Router 中使用缓存的更多信息。

选项

CORS

跨源资源共享(CORS)是一项安全功能,允许你控制哪些站点可以访问你的资源。你可以设置 Access-Control-Allow-Origin 标头,以允许特定源访问你的路由处理器。

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。使用下面的配置,所有当前及未来的子域都将在 max-age 为 2 年的时间内使用 HTTPS。这会阻止访问只能通过 HTTP 提供的页面或子域。

{
  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 添加了标头。