使用 Firebase 托管实现本地化的 404 网页



假设我的 Web 应用程序有两个区域设置:英语(myapp.com/en/(和法语(myapp.com/fr/(。我想本地化我的 404 页面,以便向myapp.com/en/non-existentmyapp.com/non-existent的请求将返回 404 页面的英文版本,而对myapp.comm/fr/non-existent的请求将返回法语版本。

但是,Firebase Hosting似乎默认情况下不提供此类功能,因为它只允许单个404页面(来源(

那么,有没有办法使用 Firebase 托管实现本地化的 404 页面?

这个答案已经过时了。Firebase 现在默认支持此功能。查看正确答案。


实现此功能的一种方法是使用重写:

{
...
"hosting": {
"rewrites": [
{
"source": "/fr/**",
"destination": "/fr/404.html"
},
{
"source": "**",
"destination": "/en/404.html"
}
]
}

这将为目录中不匹配的请求提供/fr/404.html/页面/fr/并为任何其他不匹配的请求提供/en/404.html

此方法的缺点是返回的状态代码是 200 而不是 404。


更好的解决方案是重写对云函数的不匹配请求,这些请求返回所需的 404 页面和 404 状态代码。请注意,404 页面必须位于目录中functions/lib而不是public.

此外,通过使用适当的Cache-Control标头,您可以允许 Firebase 托管缓存函数的输出,这样它们就不必在每次请求 404 页面时都运行。

火力基本配置:

{
...
"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页面的功能请求,他们回复说会考虑。

自 2020 年 8 月 12 日起,Firebase Hosting 现在包含对 i18n 内部化的支持。

以下是使用它的方法:

  1. 创建一个新目录以在public目录下托管这些本地化文件(例如localized(。
  2. 更新firebase.json文件以包含对此新目录的引用:
// firebase.json
"hosting": {
"public": "public",
"ignore": [
// ...
],
"i18n": {
"root": "/localized"  // directory that contains your "i18n content"
}
// ...
}
  1. localized目录下,创建一个名为fr的新目录,您可以在其中添加法语404.html文件。
  2. 运行firebase deploy以部署您的网站,现在您的法语用户应该被重定向到正确的页面:)

请参阅 Firebase 文档,详细了解国家/地区和语言代码。

最新更新