实现此功能的一种方法是使用rewrites:
{
...
"hosting": {
"rewrites": [
{
"source": "/fr/**",
"destination": "/fr/404.html"
},
{
"source": "**",
"destination": "/en/404.html"
}
]
}
这将为/fr/ 目录中的不匹配请求提供/fr/404.html/ 页面,为任何其他不匹配请求提供/en/404.html。
这种方法的缺点是返回的状态码是 200 而不是 404。
更好的解决方案是重写返回所需 404 页面和 404 状态码的不匹配请求 to Cloud Functions。请注意,404 页面必须位于 functions/lib 目录中,而不是 public。
此外,通过使用正确的 Cache-Control 标头,您可以允许 Firebase 托管缓存函数的输出,这样它们就不必在每次请求 404 页面时都运行。
Firebase 配置:
{
...
"hosting": {
"rewrites": [
{
"source": "/fr/**",
"function": "pageNotFoundFr"
},
{
"source": "**",
"function": "pageNotFound"
}
]
}
功能:
exports.pageNotFound = functions.https.onRequest((req, res) => {
res.set("Cache-Control", "public, max-age=31536000")
res.status(404).sendFile("en/404.html", {root: __dirname})
})
exports.pageNotFoundFr = functions.https.onRequest((req, res) => {
res.set("Cache-Control", "public, max-age=31536000")
res.status(404).sendFile("fr/404.html", {root: __dirname})
})
但是这种方法会重复代码,如果您有更多语言,可能会很混乱。
最好将请求处理程序提取到一个函数中:
exports.pageNotFound = functions.https.onRequest(notFoundHanler("en"))
exports.pageNotFoundFr = functions.https.onRequest(notFoundHanler("fr"))
function notFoundHandler(lang) {
return function (req, res) {
res.set("Cache-Control", "public, max-age=31536000")
res.status(404).sendFile(`${lang}/404.html`, {root: __dirname})
}
}
更新:我向 Firebase 提交了多个 404 页面的功能请求,他们回复说会考虑。