如何在firebase.json中配置托管行为以重写URL?

时间:2020-05-17 10:47:53

标签: javascript firebase redirect url-rewriting firebase-hosting

我正在开发一个Web应用程序,并将所有文件托管在Firebase Hosting上。

我想要有人输入此URL

mydomain.com/SomeUsername   //SomeUsername is URL Variable

它应该打开该URL

mydomain.com/user/index.html?user=SomeUsername   //SomeUsername is URL Variable

我尝试了此操作,但不起作用,将其重定向到404页面未找到。

{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [ {
    "source": "/user/index.html?user=:SomeUsername*", 
    "destination": "mydomain.com/:SomeUsername*",
    "type": 301
  }]
  }
}

2 个答案:

答案 0 :(得分:0)

请尝试从重写中删除“类型”,因为这是重写而不是重定向。另外,请尝试通过以下方式将其从目标中删除:

"mydomain.com/:SomeUsername*"

"/:SomeUsername*"

代码应显示:

 "rewrites": [ {
    "source": "/user/index.html?user=:SomeUsername*", 
    "destination": "/:SomeUsername*",

答案 1 :(得分:0)

我找到了其他解决方案,当我键入mydomain.com/SomeUsername时,它将重定向到404.html,显然该页面不可用。我编辑了404.html以重定向到实际页面。

404.html

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <script>
      const currentUrl = window.location.href;
      var a = document.createElement('a')
      a.setAttribute('href',currentUrl)
      var uname = a.pathname.replace('/','')
      window.location = "https://yourdomain/user/index.html?username="+uname;
    </script>
  </body>
</html>

和在user / index.html页

if(history.replaceState) history.replaceState({}, "", "/username"); 

只是为了显示网址mydomain.com/username