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

Max*_*Max 3 localization firebase firebase-hosting

假设我的网络应用程序有两种语言环境:英语 ( 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 Hosting 实现本地化 404 页面呢?

Max*_*Max 5

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


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

{
  ...
  "hosting": {
    "rewrites": [
      {
        "source": "/fr/**",
        "destination": "/fr/404.html"
      },
      {
        "source": "**",
        "destination": "/en/404.html"
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

这将为目录/fr/404.html/内不匹配的请求/fr/以及/en/404.html任何其他不匹配的请求提供页面服务。

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


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

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

火力地堡配置:

{
  ...
  "hosting": {
    "rewrites": [
      {
        "source": "/fr/**",
        "function": "pageNotFoundFr"
      },
      {
        "source": "**",
        "function": "pageNotFound"
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

功能:

{
  ...
  "hosting": {
    "rewrites": [
      {
        "source": "/fr/**",
        "destination": "/fr/404.html"
      },
      {
        "source": "**",
        "destination": "/en/404.html"
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

但这种方法会重复代码,并且如果您有更多语言,可能会很混乱。


最好将请求处理程序提取到一个函数中:

{
  ...
  "hosting": {
    "rewrites": [
      {
        "source": "/fr/**",
        "function": "pageNotFoundFr"
      },
      {
        "source": "**",
        "function": "pageNotFound"
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

更新:我向 Firebase 提交了多个 404 页面的功能请求,他们回复说我们会考虑这一请求。