自定义 HTTP Headers
通过 Headers 方法,你可以在对指定路径的请求响应中设置自定义 HTTP Headers。
要设置自定义 HTTP Headers,可以在 next.config.js
中使用 headers
键:
headers
是一个异步函数,期望返回一个包含对象的数组,这些对象具有 source
和 headers
属性:
source
是传入请求路径的模式。
headers
是一个响应 header 对象数组,具有 key
和 value
属性。
basePath
: false
或 undefined
- 如果为 false,则在匹配时不会包含 basePath,仅用于外部重写。
locale
: false
或 undefined
- 是否在匹配时不包含区域设置。
has
是一个包含 type
、key
和 value
属性的 has 对象 数组。
missing
是一个包含 type
、key
和 value
属性的 missing 对象 数组。
Headers 在文件系统(包括页面和 /public
文件)之前检查。
如果两个 headers 匹配相同的路径并设置相同的 header 键,最后一个 header 键将覆盖第一个。使用下面的 header,路径 /hello
将导致 header x-hello
为 world
,因为最后一个设置的值是 world
。
允许路径匹配,例如 /blog/:slug
将匹配 /blog/hello-world
(不匹配嵌套路径):
要匹配通配符路径,可以在参数后使用 *
,例如 /blog/:slug*
将匹配 /blog/a/b/c/d/hello-world
:
要匹配正则表达式路径,可以在参数后用括号包裹正则表达式,例如 /blog/:slug(\\d{1,})
将匹配 /blog/123
但不匹配 /blog/abc
:
以下字符 (
, )
, {
, }
, :
, *
, +
, ?
用于正则表达式路径匹配,因此在 source
中作为非特殊值使用时,必须在其前添加 \\
进行转义:
要仅在 Header、Cookie 或查询值也匹配 has
字段或不匹配 missing
字段时应用 header,可以使用 has
或 missing
字段。source
和所有 has
项必须匹配,所有 missing
项必须不匹配,header 才会被应用。
has
和 missing
项可以具有以下字段:
type
: String
- 必须是 header
、cookie
、host
或 query
之一。
key
: String
- 所选类型的键以进行匹配。
value
: String
或 undefined
- 要检查的值,如果未定义,则任何值都将匹配。可以使用类似正则表达式的字符串来捕获值的特定部分,例如,如果值 first-(?<paramName>.*)
用于 first-second
,则 second
可以在目标中使用 :paramName
。
当使用 basePath
支持 时,每个 source
会自动加上 basePath
,除非你在 headers 中添加 basePath: false
:
当使用 i18n
支持 时,每个 source
会自动加上配置的 locales
,除非你在 headers 中添加 locale: false
。如果使用 locale: false
,你必须在 source
前加上区域设置以正确匹配。
你不能在 next.config.js
中为页面或资源设置 Cache-Control
header,因为这些 header 在生产环境中会被覆盖,以确保响应和静态资源被有效缓存。
了解更多关于 缓存 的信息。
跨源资源共享 (CORS) 是一项安全功能,允许你控制哪些站点可以访问你的资源。你可以设置 Access-Control-Allow-Origin
header,允许特定源访问你的 路由处理程序。
这个 header 控制 DNS 预取,允许浏览器主动对外部链接、图像、CSS、JavaScript 等进行域名解析。这种预取在后台进行,因此当需要引用项目时,DNS 更有可能已被解析。这减少了用户点击链接时的延迟。
这个 header 通知浏览器应仅使用 HTTPS 访问,而不是使用 HTTP。使用以下配置,所有当前和未来的子域将在 max-age
为 2 年内使用 HTTPS。这将阻止只能通过 HTTP 访问的页面或子域。
如果你部署到 Vercel,这个 header 不是必需的,因为它会自动添加到所有部署中,除非你在 next.config.js
中声明 headers
。
这个 header 指示是否允许在 iframe
中显示站点。这可以防止点击劫持攻击。
**这个 header 已被 CSP 的 frame-ancestors
选项所取代,后者在现代浏览器中有更好的支持(参见 内容安全策略 以获取配置详情)。
这个 header 允许你控制浏览器中哪些功能和 API 可以使用。它以前被称为 Feature-Policy
。
这个 header 防止浏览器在 Content-Type
header未明确设置时尝试猜测内容类型。这可以防止允许用户上传和共享文件的网站遭受 XSS 攻击。
例如,用户尝试下载图像,但被视为不同的 Content-Type
,如可执行文件,这可能是恶意的。这个 header 也适用于下载浏览器扩展。这个 header 的唯一有效值是 nosniff
。
这个 header 控制浏览器在从当前网站(源)导航到另一个网站时包含多少信息。
了解更多关于在你的应用中添加 内容安全策略 的信息。
版本 | 变更 |
---|
v13.3.0 | 引入 missing 。 |
v10.2.0 | 引入 has 。 |
v9.5.0 | 引入 Headers 。 |