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

如何在Firebase Hosting中配置匹配HTTP主机的重写规则?

可行!这是实现方法

你的需求完全可以通过Firebase Hosting的带主机条件的重写规则来实现,不需要复杂的额外配置。下面是具体的步骤和配置示例:

1. 修改firebase.json配置

打开项目根目录的firebase.json文件,找到(或添加)hosting配置块,替换成以下内容:

{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      // 匹配test1.domain.com的所有请求,转发到对应子目录
      {
        "source": "**",
        "destination": "/test1.domain.com/**",
        "condition": {
          "host": "test1.domain.com"
        }
      },
      // 匹配test2.domain.com的所有请求,转发到对应子目录
      {
        "source": "**",
        "destination": "/test2.domain.com/**",
        "condition": {
          "host": "test2.domain.com"
        }
      },
      // 兜底规则:如果是其他域名(比如项目默认的firebaseapp.com域名),仍返回根目录的index.html
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    // 可选配置:自动去掉URL中的.html后缀
    "cleanUrls": true,
    // 可选配置:控制URL尾部是否带斜杠(根据你的需求调整)
    "trailingSlash": false
  }
}

2. 规则说明

  • condition.host: 用来精准匹配访问的域名,只有当请求来自test1.domain.com时,才会触发对应的重写规则。
  • source: "**": 匹配该域名下的所有路径(比如test1.domain.com/about、test1.domain.com/assets/style.css等)。
  • destination: "/test1.domain.com/**": 这里的**会自动替换为请求URL中的路径部分,比如访问test1.domain.com/about会指向public/test1.domain.com/about.html(开启cleanUrls的情况下),完全对应你子目录里的文件结构。

3. 本地测试(可选但推荐)

在部署前,你可以用本地服务器测试配置是否生效:

  1. 修改本地hosts文件(Windows在C:\Windows\System32\drivers\etc\hosts,Mac/Linux在/etc/hosts),添加两行:
    127.0.0.1 test1.domain.com
    127.0.0.1 test2.domain.com
    
  2. 运行firebase serve启动本地托管服务。
  3. 在浏览器访问test1.domain.com:5000,应该会加载public/test1.domain.com/index.html;访问test2.domain.com:5000则加载对应子目录的首页。

4. 部署生效

测试没问题后,运行firebase deploy --only hosting,部署完成后你的两个域名就会各自指向对应的子目录内容了。

额外优化:自定义404页面

如果想给每个域名设置独立的404页面,可以在对应子目录下添加404.html,然后在rewrites里补充规则:

// 在test1的重写规则后添加
{
  "source": "**",
  "destination": "/test1.domain.com/404.html",
  "condition": {
    "host": "test1.domain.com",
    "exists": false
  }
},
// 同理添加test2的404规则
{
  "source": "**",
  "destination": "/test2.domain.com/404.html",
  "condition": {
    "host": "test2.domain.com",
    "exists": false
  }
}

这样当访问test1.domain.com下不存在的资源时,会返回子目录里的404页面,而不是根目录的404.html。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:24:24