You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Hosting:如何基于源域名配置URL重定向规则

实现基于请求域名的Firebase Hosting重写规则

没问题,我帮你调整Firebase Hosting的配置来满足这个需求。核心是利用Firebase支持的条件重写,通过检查请求的host请求头来区分来源域名,实现不同的路由逻辑。

具体配置方案

把你的firebase.json更新成下面的结构,我已经添加了域名判断的条件:

{
  "hosting": {
    "public": "y",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      // 规则1:来自当前域名friends.com的所有请求,都指向index
      {
        "source": "**",
        "destination": "/index.html",
        "condition": "request.host == 'friends.com'"
      },
      // 规则2:来自其他域名的请求,/user路径调用HTTPS函数
      {
        "source": "/user",
        "function": "user",
        "condition": "request.host != 'friends.com'"
      },
      // 这里保留你原来的其他重写规则
      {
        "source": ...
      }
    ]
  }
}

关键细节解释

  • 规则优先级:Firebase Hosting会按重写规则的顺序从上到下匹配,所以一定要把friends.com的专属规则放在最前面,避免被后面的规则覆盖。
  • 域名匹配范围:如果你的服务还用到了子域名(比如www.friends.com),可以修改第一个规则的条件,把这些域名都包含进去:
    "condition": "request.host == 'friends.com' || request.host == 'www.friends.com'"
    
  • 函数调用验证:确保你的user HTTPS函数已经正确部署到Firebase,函数名称和配置里的"function": "user"完全一致。

测试建议

配置更新后,记得运行firebase deploy --only hosting部署生效。可以用curl工具模拟不同来源的请求测试:

# 模拟来自friends.com的请求,应该返回index.html
curl -H "Host: friends.com" https://your-firebase-hosting-domain.com/user

# 模拟来自其他域名的请求,应该触发user函数
curl -H "Host: google.com" https://your-firebase-hosting-domain.com/user

内容的提问来源于stack exchange,提问作者Relm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:15:24