标头
Headers 允许你在对指定路径的传入请求的响应中设置自定义 HTTP headers。
要设置自定义 HTTP headers,你可以在 next.config.js
中使用 headers
键:
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
是一个异步函数,需要返回一个包含 source
和 headers
属性的对象数组:
source
是传入请求路径模式。headers
是响应 header 对象的数组,包含key
和value
属性。basePath
:false
或undefined
- 如果为 false,在匹配时不会包含 basePath,仅用于外部重写。locale
:false
或undefined
- 是否在匹配时不包含语言环境。has
是一个包含type
、key
和value
属性的匹配对象数组。missing
是一个包含type
、key
和value
属性的缺失对象数组。
Headers 会在文件系统(包括页面和 /public
文件)之前进行检查。
Header 覆盖行为
如果两个 headers 匹配相同的路径并设置相同的 header 键,最后一个 header 键将覆盖第一个。使用以下 headers,路径 /hello
将导致 header x-hello
的值为 world
,因为最后设置的 header 值是 world
。
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
(不包含嵌套路径):
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
:
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
:
module.exports = {
async headers() {
return [
{
source: '/blog/:post(\\d{1,})',
headers: [
{
key: 'x-post',
value: ':post',
},
],
},
]
},
}
以下字符 (
、)
、{
、}
、:
、*
、+
、?
用于正则表达式路径匹配,因此当在 source
中用作非特殊值时,必须通过在它们前面添加 \\
来转义:
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,可以使用这些选项。source
和所有 has
项必须匹配,且所有 missing
项必须不匹配,header 才会被应用。
has
和 missing
项可以包含以下字段:
type
:String
- 必须是header
、cookie
、host
或query
之一。key
:String
- 从所选类型中匹配的键。value
:String
或undefined
- 要检查的值,如果是 undefined 则任何值都会匹配。可以使用类似正则表达式的字符串来捕获值的特定部分,例如,如果值first-(?<paramName>.*)
用于first-second
,则second
可以在目标中使用:paramName
。
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',
// 由于提供了 value 且没有使用命名捕获组
// (例如 (?<page>home)),page 值将不会在
// header 的键/值中可用
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
value: 'true',
},
],
headers: [
{
key: 'x-authorized',
value: ':authorized',
},
],
},
// 如果存在 header `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`,
// 将应用此 header
{
source: '/:path*',
has: [
{
type: 'host',
value: 'example.com',
},
],
headers: [
{
key: 'x-another-header',
value: ':authorized',
},
],
},
]
},
}
支持 basePath 的 Headers
当使用 headers 时结合 basePath
支持,每个 source
会自动添加 basePath
前缀,除非你在 header 中添加 basePath: false
:
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
当使用 headers 时结合 i18n
支持,每个 source
会自动添加前缀以处理配置的 locales
,除非你在 header 中添加 locale: false
。如果使用了 locale: false
,你必须为 source
添加语言环境前缀才能正确匹配。
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` 是默认语言环境
source: '/en',
locale: false,
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
// 这会被转换为 /(en|fr|de)/(.*) 所以不会匹配顶级
// `/` 或 `/fr` 路由,而 /:path* 会匹配
source: '/(.*)',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
]
},
}
Cache-Control
Next.js 为真正不可变的资产设置了 Cache-Control
header:public, max-age=31536000, immutable
。这不能被覆盖。这些不可变文件的文件名中包含 SHA 哈希,所以可以安全地永久缓存。例如,静态图片导入。你不能在 next.config.js
中为这些资产设置 Cache-Control
header。
但是,你可以为其他响应或数据设置 Cache-Control
header。
如果你需要重新验证已经静态生成的页面的缓存,你可以在页面的 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
中使用缓存 headers (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
header 来允许特定来源访问你的 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
此 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
选项取代,在现代浏览器中具有更好的支持(有关配置详情,请参见 Content Security Policy)。
{
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
了解更多关于向你的应用程序添加 Content Security Policy。
版本历史
版本 | 变更 |
---|---|
v13.3.0 | 添加 missing |
v10.2.0 | 添加 has |
v9.5.0 | 添加 Headers |