首页 > 解决方案 > Firebase:使用 URL 段重写为自定义 html 文件

问题描述

我的 firebase.json 文件中有以下几行:

"rewrites": [
  {
    "source": "/blog/abc",
    "destination": "/abc.html"
  },
  {
    "source": "/blog/def",
    "destination": "/def.html"
  },
  ......
  ......
]

我怎样才能使它成为类似于这样的单个语句:

"rewrites": [
  {
    "source": "/blog/:post*",
    "destination": "/:post.html"
  }
 ]

标签: firebasefirebase-hosting

解决方案


我找不到使用 firebase 云功能而不是重写为 html 文件的路径段 globbing 和捕获的参考,但是,从测试来看,它似乎不可用。

如果您确实需要在 Firebase 云功能中进行路径段通配和捕获,则为您的 url 提供简单/hack 解决方案:

    function pathSegmantVars(request, pathName, checkForQuery = true, queryName = undefined){
      // support separate path vs query string var names
      const query = queryName ? queryName : pathName
    
      // If requested, use the query var if it exists
      if(checkForQuery && request.query[query]) {
        return request.query[query]
      }
    
      // Else check the path for the pathName variable
      const path = request.path
      const paths = path.split("/")
    
      if(paths.indexOf(pathName) && paths[paths.indexOf(pathName) + 1]){
        return paths[paths.indexOf(pathName) + 1]
      }
    
      throw new Error('Bad ' + query);
    }

并在 firebase.json 中设置如下:

"rewrites": [
 { "source": "/project/:projectId/assets", "function": "getProjectAssets" },
]

然后像这样称呼它:

    const projectId = pathSegmantVars(request, 'project');

注意 :projectId 段名称在云函数中未解析,pathSegmantVars 匹配上一个路径段(例如“项目”)。

然后从 更改curl foo.com/assets?project=1234curl foo.com/project/1234/assets

如果有人知道如何在没有这种 hack 的情况下在 firebase 中捕获路径段,我会全神贯注。或者谷歌,我可以有 cloud fn glob capture 吗?


推荐阅读