跳到内容

headers

Headers 允许你在给定路径的传入请求的响应中设置自定义 HTTP header。

要设置自定义 HTTP header,你可以使用 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 是一个异步函数,它期望返回一个数组,数组中包含带有 sourceheaders 属性的对象。

  • source 是传入请求的路径模式。
  • headers 是一个响应 header 对象数组,包含 keyvalue 属性。
  • basePath: falseundefined - 如果为 false,则在匹配时不会包含 basePath,仅可用于外部重写。
  • locale: falseundefined - 是否在匹配时不应包含 locale。
  • has 是一个 has 对象数组,包含 typekeyvalue 属性。
  • missing 是一个 missing 对象数组,包含 typekeyvalue 属性。

Headers 在文件系统(包括 pages 和 /public 文件)之前被检查。

Header 覆盖行为

如果两个 header 匹配相同的路径并设置相同的 header 键,则最后一个 header 键将覆盖第一个。使用以下 header,路径 /hello 将导致 header x-hello 的值为 world,因为最后一个设置的 header 值为 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',
          },
        ],
      },
    ]
  },
}

通配符路径匹配

要匹配通配符路径,你可以在参数后使用 *,例如 /blog/:slug* 将匹配 /blog/a/b/c/d/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',
          },
        ],
      },
    ]
  },
}

正则表达式路径匹配

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

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

要仅在 header、cookie 或 query 值也匹配 has 字段或不匹配 missing 字段时才应用 header,可以使用 has 字段或 missing 字段。要应用 header,source 和所有 has 项都必须匹配,并且所有 missing 项都不得匹配。

hasmissing 项可以具有以下字段

  • type: String - 必须是 headercookiehostquery 之一。
  • key: String - 要匹配的所选类型的键。
  • value: Stringundefined - 要检查的值,如果为 undefined,则任何值都将匹配。可以使用类似正则表达式的字符串来捕获值的特定部分,例如,如果值 first-(?<paramName>.*) 用于 first-second,则 second 将可在目标中使用 :paramName
next.config.js
module.exports = {
  async 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 的 Headers

当使用 basePath 支持 的 headers 时,每个 source 会自动添加 basePath 前缀,除非你向 header 添加 basePath: false

next.config.js
module.exports = {
  basePath: '/docs',
 
  async 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 的 Headers

当使用 i18n 支持 的 headers 时,每个 source 会自动添加前缀以处理配置的 locales,除非你向 header 添加 locale: false。如果使用 locale: false,则必须在 source 前面添加 locale 才能正确匹配。

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

Cache-Control

对于真正不可变的资源,Next.js 将 Cache-Control header 设置为 public, max-age=31536000, immutable。它无法被覆盖。这些不可变的文件在文件名中包含 SHA-hash,因此可以安全地无限期缓存。例如,静态图像导入。你不能在 next.config.js 中为这些资源设置 Cache-Control header。

但是,你可以为其他响应或数据设置 Cache-Control header。

如果你需要重新验证已静态生成的页面的缓存,你可以通过在页面的 getStaticProps 函数中设置 revalidate 属性来实现。

要缓存来自 API 路由 的响应,你可以使用 res.setHeader

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'
 
type ResponseData = {
  message: string
}
 
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.setHeader('Cache-Control', 's-maxage=86400')
  res.status(200).json({ message: 'Hello from Next.js!' })
}

你也可以在 getServerSideProps 内部使用缓存 header (Cache-Control) 来缓存动态响应。例如,使用 stale-while-revalidate

pages/index.tsx
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
 
// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export const getServerSideProps = (async (context) => {
  context.res.setHeader(
    'Cache-Control',
    'public, s-maxage=10, stale-while-revalidate=59'
  )
 
  return {
    props: {},
  }
}) satisfies GetServerSideProps

选项

CORS

跨源资源共享 (CORS) 是一项安全功能,允许你控制哪些站点可以访问你的资源。你可以设置 Access-Control-Allow-Origin header 以允许特定源访问你的API 端点.

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

此 header 控制 DNS 预获取,允许浏览器主动对外部链接、图像、CSS、JavaScript 等执行域名解析。此预获取在后台执行,因此 DNS 更可能在需要引用的项目时被解析。这减少了用户单击链接时的延迟。

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

Strict-Transport-Security

此 header 通知浏览器应该仅使用 HTTPS 访问,而不是使用 HTTP。使用以下配置,所有当前和未来的子域将在 2 年的 max-age 内使用 HTTPS。这阻止了访问只能通过 HTTP 提供的页面或子域。

如果你部署到 Vercel,则此 header 不是必需的,因为它会自动添加到所有部署中,除非你在 next.config.js 中声明 headers

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

X-Frame-Options

此 header 指示是否应允许站点在 iframe 中显示。这可以防止点击劫持攻击。

此 header 已被 CSP 的 frame-ancestors 选项取代,后者在现代浏览器中具有更好的支持(有关配置详细信息,请参阅内容安全策略)。

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

Permissions-Policy

此 header 允许你控制在浏览器中使用哪些功能和 API。它以前名为 Feature-Policy

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

X-Content-Type-Options

此 header 阻止浏览器在未显式设置 Content-Type header 时尝试猜测内容类型。这可以防止允许用户上传和共享文件的网站遭受 XSS 攻击。

例如,用户尝试下载图像,但图像被视为不同的 Content-Type,例如可执行文件,这可能是恶意的。此 header 也适用于下载浏览器扩展。此 header 的唯一有效值为 nosniff

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

Referrer-Policy

此 header 控制浏览器在从当前网站(源)导航到另一个网站时包含多少信息。

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

Content-Security-Policy

了解更多关于向你的应用程序添加 内容安全策略 的信息。

版本历史

版本变更
v13.3.0添加了 missing
v10.2.0添加了 has
v9.5.0添加了 Headers。