How to Configure Redirects in Firebase Hosting
To configure redirects in Firebase Hosting, add a
redirects array in your firebase.json file under the hosting section. Each redirect defines a source URL pattern and a destination URL, with an optional type for HTTP status code like 301 or 302.Syntax
The redirects section in firebase.json defines rules to send visitors from one URL to another. Each rule has:
- source: The URL pattern to match (can use wildcards).
- destination: The URL to redirect to.
- type: The HTTP status code for the redirect (301 for permanent, 302 for temporary). Default is 302.
json
{
"hosting": {
"redirects": [
{
"source": "/old-path",
"destination": "/new-path",
"type": 301
}
]
}
}Example
This example shows how to redirect visitors from /blog to /news permanently using a 301 redirect, and how to redirect all URLs under /docs/* to /documentation/* temporarily.
json
{
"hosting": {
"public": "public",
"redirects": [
{
"source": "/blog",
"destination": "/news",
"type": 301
},
{
"source": "/docs/**",
"destination": "/documentation/**",
"type": 302
}
]
}
}Output
When a user visits /blog, they are permanently redirected to /news.
When a user visits /docs/anything, they are temporarily redirected to /documentation/anything.
Common Pitfalls
Common mistakes when configuring redirects include:
- Forgetting to deploy after changing
firebase.jsonwithfirebase deploy. - Using incorrect wildcard syntax; use
**to match multiple path segments. - Not specifying
typedefaults to 302, which may not be intended. - Redirect loops if source and destination overlap incorrectly.
json
{
"hosting": {
"redirects": [
{
"source": "/page",
"destination": "/page",
"type": 301
}
]
}
}
// This causes a redirect loop because source and destination are the same.
// Correct way:
{
"hosting": {
"redirects": [
{
"source": "/page-old",
"destination": "/page-new",
"type": 301
}
]
}
}Quick Reference
| Field | Description | Example |
|---|---|---|
| source | URL pattern to match (supports wildcards) | /old-path or /docs/** |
| destination | URL to redirect to | /new-path or /documentation/** |
| type | HTTP status code for redirect (301 or 302) | 301 for permanent, 302 for temporary |
Key Takeaways
Add redirects in the hosting section of firebase.json using source, destination, and type.
Use 301 for permanent and 302 for temporary redirects to control browser caching.
Wildcards like ** help redirect multiple paths at once.
Always run firebase deploy after updating redirects to apply changes.
Avoid redirect loops by ensuring source and destination URLs differ.