firebase - 使用 Firebase 托管实现本地化 404 页面

标签 firebase localization firebase-hosting

假设我的网络应用有两个语言环境:英语 (myapp.com/en/) 和法语 (myapp.com/fr/)。我想本地化我的 404 页面,以便对 myapp.com/en/non-existentmyapp.com/non-existent 的请求将返回英文版404 页面和对 myapp.comm/fr/non-existent 的请求将返回法语页面。

但是,Firebase 托管似乎默认不提供此类功能,因为它只允许单个 404 页面 (source)

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

最佳答案

这个答案已经过时了。 Firebase 现在默认支持此功能。见 the correct answer .


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

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

这将为 /fr/ 目录和 /en/404.html 内的不匹配请求提供 /fr/404.html/ 页面> 对于任何其他不匹配的请求。

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


更好的解决方案是重写不匹配的请求 to Cloud Functions返回所需的 404 页面和 404 状态码。请注意,404 页面必须位于 functions/lib 目录,而不是 public

此外,通过使用正确的 Cache-Control header ,您可以允许 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 页面的功能请求,他们回复说会考虑。

关于firebase - 使用 Firebase 托管实现本地化 404 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62177351/

相关文章:

firebase - 将子域连接到 firebase

angular - ng-build 上的端口和代理配置

ios - Facebook 登录 UIView 加载异常,而 UI 行为符合预期

firebase - 如果保留为空,如何不将字段保存到Firebase

python - Django DATETIME_FORMAT 特定日期不正确(一年)

Firebase 托管,创建 404 页面

python - 传感器Python DHT11

angularjs - 当 session 在Firebase中过期时,如何使用UI路由器重定向

WPF XAML 绑定(bind)和 CurrentCulture 显示

angular - 从 typescript 中提取 $localize 消息在 Angular 9 中不起作用