Search code examples
firebasefirebase-hosting

Configure redirects on Firebase Hosting SPA + 2 subfolders firebase.json


I have a public folder like:

/public
   index.html

   /landing
     index.html

   /membership
     index.html

/public/index.html is a SPA, so each request to /** should me rewritten to /index.html

/landing/ and /membership/ are two static HTML landings so each request should not be rewritten

firebase.json suggested by Google support:

{
    "functions": {
        "source": "functions"
    },
    "hosting": {
        "public": "public",
        "redirects": [{
                "source": "/landing",
                "destination": "index.html"
            },
            {
                "source": "/membership",
                "destination": "index.html"
            }
        ],
        "rewrites": [{
                "source": "/membership/**",
                "destination": "/membership/index.html"
            }
        ],
        "ignore": [
            "firebase.json",
            "**/.*",
            "**/node_modules/**"
        ]
    }
}

Everything just gets redirected to /index.html...

Even tried with:

{
  "functions": {
      "source": "functions"
  },
  "hosting": {
      "public": "public",
      "redirects": [{
              "source": "/landing/**",
              "destination": "/landing/index.html"
          },
          {
              "source": "/membership/**",
              "destination": "/membership/index.html"
          }
      ],
      "rewrites": [{
              "source": "**",
              "destination": "/index.html"
          }
      ],
      "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
      ]
  }
}

Same result, everything just goes to /


Solution

  • You don't have to use "redirects". Juste use these rewrites rules :

    {
        "functions": {
            "source": "functions"
        },
        "hosting": {
            "public": "public",
            "ignore": [
                "firebase.json",
                "**/.*",
                "**/node_modules/**"
            ],
            "rewrites": [
                {
                    "source": "!/@(landing|membership)/**",
                    "destination": "/index.html"
                },
                {
                    "source": "/landing/**",
                    "destination": "/landing/index.html"
                },
                {
                    "source": "/membership/**",
                    "destination": "/membership/index.html"
                }
            ]
        }
    }
    

    The first rule will rewrite everything except what is starting with landing OR membership. The second rule will take care of the landing paths. And the third will specify what to do with all of the membership paths.