Menu

自定义 HTTP Headers

通过 Headers 方法,你可以在对指定路径的请求响应中设置自定义 HTTP Headers。

要设置自定义 HTTP Headers,可以在 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 - 是否在匹配时不包含区域设置。
  • has 是一个包含 typekeyvalue 属性的 has 对象 数组。
  • missing 是一个包含 typekeyvalue 属性的 missing 对象 数组。

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

Header 覆盖行为

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

Header、Cookie 和查询匹配

要仅在 Header、Cookie 或查询值也匹配 has 字段或不匹配 missing 字段时应用 header,可以使用 hasmissing 字段。source 和所有 has 项必须匹配,所有 missing 项必须不匹配,header 才会被应用。

hasmissing 项可以具有以下字段:

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

带有 basePath 支持的 Headers

当使用 basePath 支持 时,每个 source 会自动加上 basePath,除非你在 headers 中添加 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 支持的 Headers

当使用 i18n 支持 时,每个 source 会自动加上配置的 locales,除非你在 headers 中添加 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.config.js 中为页面或资源设置 Cache-Control header,因为这些 header 在生产环境中会被覆盖,以确保响应和静态资源被有效缓存。

了解更多关于 缓存 的信息。

选项

CORS

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

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

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

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

Strict-Transport-Security

这个 header 通知浏览器应仅使用 HTTPS 访问,而不是使用 HTTP。使用以下配置,所有当前和未来的子域将在 max-age 为 2 年内使用 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