如何在Firebase中隐藏网址不必要子文件夹并缩短URL
/htmlfolder/ from Firebase Hosting URL Without Moving index.html Absolutely! You don’t need to relocate your index.html out of the htmlfolder subdirectory to get the clean URL you want. Firebase Hosting’s URL rewrite rules are the perfect solution here—they work server-side, so you won’t run into the refresh issues you had with client-side window.history.pushState().
Here’s exactly how to set it up:
Step 1: Edit your firebase.json configuration
In your project’s root directory, find the firebase.json file (this is where all Firebase Hosting settings live). You’ll need to add a rewrites section to the hosting object.
Example configuration
If you just want the root /index.html (or the bare domain path /) to map to your htmlfolder/index.html, use this setup:
{ "hosting": { "public": "public", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ // Maps both the bare domain and /index.html to your target file { "source": "/", "destination": "/htmlfolder/index.html" }, { "source": "/index.html", "destination": "/htmlfolder/index.html" } ] } }
If you’re building a single-page app (SPA) where all routes should point to that index.html, you can simplify it to a catch-all rule:
"rewrites": [ { "source": "**", "destination": "/htmlfolder/index.html" } ]
Step 2: Deploy the updated configuration
Once you’ve saved the changes to firebase.json, run this command in your terminal to push the new hosting settings live:
firebase deploy --only hosting
Why this works better than pushState()
Unlike client-side history manipulation, these rewrites happen on Firebase’s servers. That means:
- Users can refresh the page or directly type
www.lstein-28b62.web.app/index.htmlinto their browser, and they’ll still land on the correct page (no 404 errors). - The URL stays clean and hides the
/htmlfolder/path entirely from visitors.
Quick checks to avoid issues
- Double-check that your
index.htmlis indeed located atpublic/htmlfolder/index.html(matches your project’s folder structure). - If you have other pages in
htmlfolderthat need clean URLs, add additional rewrite rules for each path (e.g.,{"source": "/about", "destination": "/htmlfolder/about.html"}).
内容的提问来源于stack exchange,提问作者floflo8

