rewrites
Rewrites 允許你將傳入的請求路徑映射到不同的目標路徑。
Rewrites 作為 URL 代理並遮蔽目標路徑,使其看起來使用者沒有更改網站上的位置。 相反地,redirects 會重新路由到新頁面並顯示 URL 變更。
若要使用 rewrites,你可以在 next.config.js
中使用 rewrites
鍵
module.exports = {
async rewrites() {
return [
{
source: '/about',
destination: '/',
},
]
},
}
Rewrites 適用於用戶端路由,在上面的範例中,<Link href="/about">
將套用 rewrite。
rewrites
是一個非同步函式,預期會傳回陣列或陣列的物件(請參閱下方),其中包含具有 source
和 destination
屬性的物件
source
:String
- 是傳入的請求路徑模式。destination
:String
是你想要路由到的路徑。basePath
:false
或undefined
- 若為 false,則比對時不會包含 basePath,僅可用於外部 rewrites。locale
:false
或undefined
- 是否在比對時不應包含語系。has
是 has 物件 的陣列,具有type
、key
和value
屬性。missing
是 missing 物件 的陣列,具有type
、key
和value
屬性。
當 rewrites
函式傳回陣列時,rewrites 會在檢查檔案系統(pages 和 /public
檔案)之後以及在動態路由之前套用。 當 rewrites
函式傳回具有特定形狀的陣列物件時,此行為可以變更並更精細地控制,從 Next.js 的 v10.1
版本開始。
module.exports = {
async rewrites() {
return {
beforeFiles: [
// These rewrites are checked after headers/redirects
// and before all files including _next/public files which
// allows overriding page files
{
source: '/some-page',
destination: '/somewhere-else',
has: [{ type: 'query', key: 'overrideMe' }],
},
],
afterFiles: [
// These rewrites are checked after pages/public files
// are checked but before dynamic routes
{
source: '/non-existent',
destination: '/somewhere-else',
},
],
fallback: [
// These rewrites are checked after both pages/public files
// and dynamic routes are checked
{
source: '/:path*',
destination: `https://my-old-site.com/:path*`,
},
],
}
},
}
要知道的好處:
beforeFiles
中的 rewrites 不會在比對到來源後立即檢查檔案系統/動態路由,它們會繼續直到所有beforeFiles
都已檢查完畢。
Next.js 路由檢查的順序為
- headers 已檢查/已套用
- redirects 已檢查/已套用
beforeFiles
rewrites 已檢查/已套用- 來自 public 目錄、
_next/static
檔案和非動態頁面的靜態檔案已檢查/已提供服務 afterFiles
rewrites 已檢查/已套用,如果比對到其中一個 rewrites,我們會在每次比對後檢查動態路由/靜態檔案fallback
rewrites 已檢查/已套用,這些會在渲染 404 頁面之前以及在動態路由/所有靜態資源都已檢查完畢之後套用。 如果你在getStaticPaths
中使用 fallback: true/'blocking',則在你的next.config.js
中定義的 fallbackrewrites
將不會執行。
Rewrite 參數
當在 rewrite 中使用參數時,如果 destination
中未使用任何參數,則預設會將參數傳遞到查詢中。
module.exports = {
async rewrites() {
return [
{
source: '/old-about/:path*',
destination: '/about', // The :path parameter isn't used here so will be automatically passed in the query
},
]
},
}
如果在 destination 中使用了參數,則不會自動將任何參數傳遞到查詢中。
module.exports = {
async rewrites() {
return [
{
source: '/docs/:path*',
destination: '/:path*', // The :path parameter is used here so will not be automatically passed in the query
},
]
},
}
如果 destination 中已使用參數,你仍然可以透過在 destination
中指定查詢,手動將參數傳遞到查詢中。
module.exports = {
async rewrites() {
return [
{
source: '/:first/:second',
destination: '/:first?second=:second',
// Since the :first parameter is used in the destination the :second parameter
// will not automatically be added in the query although we can manually add it
// as shown above
},
]
},
}
要知道的好處:來自 自動靜態最佳化 或 預先渲染 的靜態頁面參數將在 hydration 後於用戶端上解析,並在查詢中提供。
路徑匹配
允許路徑匹配,例如 /blog/:slug
將比對 /blog/hello-world
(沒有巢狀路徑)
module.exports = {
async rewrites() {
return [
{
source: '/blog/:slug',
destination: '/news/:slug', // Matched parameters can be used in the destination
},
]
},
}
萬用字元路徑匹配
若要比對萬用字元路徑,你可以在參數後使用 *
,例如 /blog/:slug*
將比對 /blog/a/b/c/d/hello-world
module.exports = {
async rewrites() {
return [
{
source: '/blog/:slug*',
destination: '/news/:slug*', // Matched parameters can be used in the destination
},
]
},
}
正則表達式路徑匹配
若要比對正則表達式路徑,你可以將正則表達式包在參數後的括號中,例如 /blog/:slug(\\d{1,})
將比對 /blog/123
但不會比對 /blog/abc
module.exports = {
async rewrites() {
return [
{
source: '/old-blog/:post(\\d{1,})',
destination: '/blog/:post', // Matched parameters can be used in the destination
},
]
},
}
以下字元 (
、)
、{
、}
、[
、]
、|
、\
、^
、.
、:
、*
、+
、-
、?
、$
用於正則表達式路徑匹配,因此當在 source
中作為非特殊值使用時,必須透過在它們之前新增 \\
來逸出
module.exports = {
async rewrites() {
return [
{
// this will match `/english(default)/something` being requested
source: '/english\\(default\\)/:slug',
destination: '/en-us/:slug',
},
]
},
}
Header、Cookie 和 Query 匹配
為了僅在 header、cookie 或 query 值也符合 has
欄位或不符合 missing
欄位時比對 rewrite,可以使用 has
欄位或 missing
欄位。 source
和所有 has
項目都必須比對,且所有 missing
項目都不得比對,才能套用 rewrite。
has
和 missing
項目可以具有以下欄位
type
:String
- 必須是header
、cookie
、host
或query
其中之一。key
:String
- 要比對的所選類型中的鍵。value
:String
或undefined
- 要檢查的值,如果為 undefined,則任何值都將比對。 可以使用類似正則表達式的字串來擷取值的特定部分,例如,如果first-(?<paramName>.*)
值用於first-second
,則second
將可在 destination 中與:paramName
一起使用。
module.exports = {
async rewrites() {
return [
// if the header `x-rewrite-me` is present,
// this rewrite will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-rewrite-me',
},
],
destination: '/another-page',
},
// if the header `x-rewrite-me` is not present,
// this rewrite will be applied
{
source: '/:path*',
missing: [
{
type: 'header',
key: 'x-rewrite-me',
},
],
destination: '/another-page',
},
// if the source, query, and cookie are matched,
// this rewrite will be applied
{
source: '/specific/:path*',
has: [
{
type: 'query',
key: 'page',
// the page value will not be available in the
// destination since value is provided and doesn't
// use a named capture group e.g. (?<page>home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
value: 'true',
},
],
destination: '/:path*/home',
},
// if the header `x-authorized` is present and
// contains a matching value, this rewrite will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-authorized',
value: '(?<authorized>yes|true)',
},
],
destination: '/home?authorized=:authorized',
},
// if the host is `example.com`,
// this rewrite will be applied
{
source: '/:path*',
has: [
{
type: 'host',
value: 'example.com',
},
],
destination: '/another-page',
},
]
},
}
重寫到外部 URL
Rewrites 允許你重寫到外部 URL。 這對於增量採用 Next.js 特別有用。 以下是將主應用程式的 /blog
路由重新導向到外部網站的範例 rewrite。
module.exports = {
async rewrites() {
return [
{
source: '/blog',
destination: 'https://example.com/blog',
},
{
source: '/blog/:slug',
destination: 'https://example.com/blog/:slug', // Matched parameters can be used in the destination
},
]
},
}
如果你使用 trailingSlash: true
,你也需要在 source
參數中插入尾部斜線。 如果目標伺服器也預期尾部斜線,則應將其包含在 destination
參數中。
module.exports = {
trailingSlash: true,
async rewrites() {
return [
{
source: '/blog/',
destination: 'https://example.com/blog/',
},
{
source: '/blog/:path*/',
destination: 'https://example.com/blog/:path*/',
},
]
},
}
Next.js 的增量採用
你也可以讓 Next.js 在檢查完所有 Next.js 路由後,回退到代理到現有網站。
這樣,當你將更多頁面遷移到 Next.js 時,就不必更改 rewrites 設定。
module.exports = {
async rewrites() {
return {
fallback: [
{
source: '/:path*',
destination: `https://custom-routes-proxying-endpoint.vercel.app/:path*`,
},
],
}
},
}
具有 basePath 支援的 Rewrites
當搭配 basePath
支援 使用 rewrites 時,每個 source
和 destination
都會自動加上 basePath
前綴,除非你將 basePath: false
新增至 rewrite
module.exports = {
basePath: '/docs',
async rewrites() {
return [
{
source: '/with-basePath', // automatically becomes /docs/with-basePath
destination: '/another', // automatically becomes /docs/another
},
{
// does not add /docs to /without-basePath since basePath: false is set
// Note: this can not be used for internal rewrites e.g. `destination: '/another'`
source: '/without-basePath',
destination: 'https://example.com',
basePath: false,
},
]
},
}
具有 i18n 支援的 Rewrites
當搭配 i18n
支援 使用 rewrites 時,每個 source
和 destination
都會自動加上前綴以處理設定的 locales
,除非你將 locale: false
新增至 rewrite。 如果使用 locale: false
,你必須在 source
和 destination
前面加上語系,才能正確比對。
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async rewrites() {
return [
{
source: '/with-locale', // automatically handles all locales
destination: '/another', // automatically passes the locale on
},
{
// does not handle locales automatically since locale: false is set
source: '/nl/with-locale-manual',
destination: '/nl/another',
locale: false,
},
{
// this matches '/' since `en` is the defaultLocale
source: '/en',
destination: '/en/another',
locale: false,
},
{
// it's possible to match all locales even when locale: false is set
source: '/:locale/api-alias/:path*',
destination: '/api/:path*',
locale: false,
},
{
// this gets converted to /(en|fr|de)/(.*) so will not match the top-level
// `/` or `/fr` routes like /:path* would
source: '/(.*)',
destination: '/another',
},
]
},
}
版本歷史
版本 | 變更 |
---|---|
v13.3.0 | 新增 missing 。 |
v10.2.0 | 新增 has 。 |
v9.5.0 | 新增 Headers。 |
這有幫助嗎?