Search code examples
firebasefirebase-hosting

How to enforce trailing slash in Firebase hosting for directories only


I am using Firebase Hosting with cleanUrls.

Firebase Hosting also allows to enforce trailing slashes in all URLs with:

"hosting": {
  "trailingSlash": true
}

This will force a 301 redirect if the user requests a page without using a trailing slash. However, I'd like to enforce this redirect only for directories (i.e.: for serving index.html files).

According the documentation, you can leave trailingSlash as undefined. This will:

  • Serve /foo/bar/page with a 200 (/foo/bar/page.html)
  • Serve /foo/bar/ with a 200 (/foo/bar/index.html)
  • Serve /foo/bar with a 200 (/foo/bar/index.html)

The last part is unexpected, since I'd like to enforce trailing slashes for directories.

How can I enforce a 301 redirection for all directories to enforce a trailing slash only for them? In example:

  • Serve /foo/bar/page with a 200 (/foo/bar/page.html)
  • Serve /foo/bar/ with a 200 (/foo/bar/index.html)
  • Redirect /foo/bar with a 301 to /foo/bar/

Note there can be many directories so a solution that avoids writing a separate rule for each one is much preferred for maintainability.

Having /foo/bar return a 404 would be okay too, but 301 is preferred.


Solution

  • As of 2024-04-04, there does not seem to be a solution for this problem:

    • Redirections using redirects in firebase.json do not work as expected (result in infinite redirections)
    • @vonc's answer suggests using an intermediate Cloud Function solution which:
      • Has not been tested (maybe it does not work)
      • Is not suitable for many cases like mine, where that would introduce unwanted higher latencies (specially for cold starts) and higher complexity and maintenance costs

    The issue/feature request was reported to Firebase support.