Search code examples
javascriptfirebasehttp-redirecturl-rewritingfirebase-hosting

How to Configure hosting behavior in firebase.json to rewrite URL?


I am developing a web app and hosted all files on Firebase Hosting.

I want when someone type this URL

mydomain.com/SomeUsername   //SomeUsername is URL Variable

it should open this URL

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

I tried this but not working, Its redirecting to 404 Page Not Found.

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

Solution

  • I found other solution, When I type mydomain.com/SomeUsername It will redirect me to 404.html which is obvious this page is not available. I edited 404.html to redirect to actual page.

    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>
    

    and in user/index.html page

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

    just to show url look like this mydomain.com/username