headers

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

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

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/about',
        headers: [
          {
            key: 'x-custom-header',
            value: '我的自定义标头值',
          },
          {
            key: 'x-another-custom-header',
            value: '我的其他自定义标头值',
          },
        ],
      },
    ]
  },
}

headers 是一个异步函数,需要返回一个包含具有 sourceheaders 属性的对象数组:

  • source:传入请求的路径模式
  • headers:响应标头对象数组,包含 keyvalue 属性
  • basePathfalseundefined - 如果为 false,则匹配时不包含 basePath,仅用于外部重写
  • localefalseundefined - 匹配时是否不包含语言环境
  • has:包含 typekeyvalue 属性的 has 对象 数组
  • missing:包含 typekeyvalue 属性的 missing 对象 数组

标头检查优先于文件系统(包括页面和 /public 文件)。

标头覆盖行为

如果两个标头匹配相同路径并设置相同的标头键,后一个标头键会覆盖前一个。使用以下标头配置时,路径 /hello 将导致标头 x-hello 的值为 world,因为最后设置的标头值是 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', // 匹配的参数可用于值中
          },
          {
            key: 'x-slug-:slug', // 匹配的参数可用于键中
            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*', // 匹配的参数可用于值中
          },
          {
            key: 'x-slug-:slug*', // 匹配的参数可用于键中
            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 [
      {
        // 这将匹配请求的 `/english(default)/something`
        source: '/english\\(default\\)/:slug',
        headers: [
          {
            key: 'x-header',
            value: 'value',
          },
        ],
      },
    ]
  },
}

标头、Cookie 和查询匹配

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

hasmissing 项可以包含以下字段:

  • typeString - 必须是 headercookiehostquery 之一
  • keyString - 要匹配的选定类型的键
  • valueStringundefined - 要检查的值,如果未定义则匹配任何值。可以使用类似正则表达式的字符串捕获值的特定部分,例如如果值 first-(?<paramName>.*) 用于 first-second,则 second 可以在目标中使用 :paramName
next.config.js
module.exports = {
  async headers() {
    return [
      // 如果存在标头 `x-add-header`,
      // 将应用 `x-another-header` 标头
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-add-header',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: 'hello',
          },
        ],
      },
      // 如果不存在标头 `x-no-header`,
      // 将应用 `x-another-header` 标头
      {
        source: '/:path*',
        missing: [
          {
            type: 'header',
            key: 'x-no-header',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: 'hello',
          },
        ],
      },
      // 如果匹配了源、查询和 cookie,
      // 将应用 `x-authorized` 标头
      {
        source: '/specific/:path*',
        has: [
          {
            type: 'query',
            key: 'page',
            // 由于提供了值且未使用命名捕获组(例如 (?<page>home),
            // 页面值将不可用于标头键/值
            value: 'home',
          },
          {
            type: 'cookie',
            key: 'authorized',
            value: 'true',
          },
        ],
        headers: [
          {
            key: 'x-authorized',
            value: ':authorized',
          },
        ],
      },
      // 如果标头 `x-authorized` 存在且
      // 包含匹配值,将应用 `x-another-header`
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: ':authorized',
          },
        ],
      },
      // 如果主机是 `example.com`,
      // 将应用此标头
      {
        source: '/:path*',
        has: [
          {
            type: 'host',
            value: 'example.com',
          },
        ],
        headers: [
          {
            key: 'x-another-header',
            value: ':authorized',
          },
        ],
      },
    ]
  },
}

支持 basePath 的标头

当与标头一起使用 basePath 支持 时,每个 source 会自动添加 basePath 前缀,除非你在标头中添加 basePath: false

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

  async headers() {
    return [
      {
        source: '/with-basePath', // 变为 /docs/with-basePath
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        source: '/without-basePath', // 由于设置了 basePath: false,不会被修改
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
        basePath: false,
      },
    ]
  },
}

支持 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', // 自动处理所有语言环境
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // 由于设置了 locale: false,不自动处理语言环境
        source: '/nl/with-locale-manual',
        locale: false,
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // 匹配 '/',因为 `en` 是 defaultLocale
        source: '/en',
        locale: false,
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
      {
        // 这将转换为 /(en|fr|de)/(.*),因此不会像 /:path* 那样匹配顶级 `/` 或 `/fr` 路由
        source: '/(.*)',
        headers: [
          {
            key: 'x-hello',
            value: 'world',
          },
        ],
      },
    ]
  },
}

Cache-Control

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

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

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

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

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 中使用缓存标头(Cache-Control)来缓存动态响应。例如,使用 stale-while-revalidate

import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'

// 此值在十秒内被视为新鲜(s-maxage=10)。
// 如果在接下来的 10 秒内重复请求,之前缓存的值仍将是新鲜的。如果在 59 秒前重复请求,
// 缓存的值将是过时的但仍会渲染(stale-while-revalidate=59)。
//
// 在后台,将发出重新验证请求以用新值填充缓存。
// 如果刷新页面,你将看到新值。
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 标头以允许特定来源访问你的 API 端点

async headers() {
    return [
      {
        source: "/api/:path*",
        headers: [
          {
            key: "Access-Control-Allow-Origin",
            value: "*", // 设置你的来源
          },
          {
            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 提供的页面或子域。

{
  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-内容类型选项 (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)

详细了解如何为您的应用添加 内容安全策略 (Content Security Policy)

版本历史

版本变更内容
v13.3.0新增 missing
v10.2.0新增 has
v9.5.0新增头部字段。