boolean | HistoryApiFallbackOptions
false
historyApiFallback
用于支持基于 history API 的路由,当用户访问不存在的路径时,自动返回指定的 HTML 文件,避免出现 404 错误。
当 Rsbuild 默认的 页面路由 行为无法满足你的需求时,例如,希望在访问 /
时可以访问 main.html
,你可以通过 server.historyApiFallback
配置项来实现这个功能。
将 server.historyApiFallback
设置为 true
时,所有未匹配到实际资源的 HTML GET 请求都会返回 index.html
,从而保证单页应用的路由能够正常工作。
export default {
server: {
historyApiFallback: true,
},
};
当满足以下条件时,Rsbuild 会将请求的路径重定向到你指定的 index 文件:
GET
或 HEAD
text/html
.
,即不是直接的文件请求server.historyApiFallback
也支持传入一个对象来自定义行为。
string
'index.html'
通过将 historyApiFallback.index
设置为 main.html
,当访问根路径 /
或其他可能导致 404 的路由时,页面会自动重定向到 main.html
。
export default {
source: {
entry: {
main: './src/index.ts',
},
},
server: {
htmlFallback: false,
historyApiFallback: {
index: '/main.html',
},
},
};
type Rewrites = Array<{
from: RegExp;
to: string | ((context: HistoryApiFallbackContext) => string);
}>;
[]
当你的应用包含多个入口(entry)时,你可能需要将不同的访问路径重定向到不同的页面。此时,你可以通过 rewrites
选项来配置更灵活的重定向规则:
export default {
server: {
historyApiFallback: {
rewrites: [
{ from: /^\/$/, to: '/views/landing.html' },
{ from: /^\/subpage/, to: '/views/subpage.html' },
{ from: /./, to: '/views/404.html' },
],
},
},
};
string[]
['text/html', '*/*']
用于覆盖匹配 HTML 内容请求时默认查询的 Accepts:
请求头。
export default {
server: {
historyApiFallback: {
htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],
},
},
};
boolean
false
默认情况下,路径中包含点(.
)的请求会被视为直接的文件请求,不会被重定向。
将 disableDotRule
设置为 true
后,这一行为会被关闭,此类请求也会被重定向。
export default {
server: {
historyApiFallback: {
disableDotRule: true,
},
},
};