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

Firebase Hosting子域名部署问题:配置dashboard子域名及权限设置

解决Firebase Hosting子域名认证访问问题

首先明确:你无法直接添加dashboard.<PROJECT_NAME>.web.app作为自定义域名,因为web.app是Firebase官方托管域名,用户没有权限修改其DNS配置或添加自定义子域名。以下是两种可行替代方案:

方案一:使用路径路由+认证拦截(推荐,无需额外域名)

利用React路由配合Firebase Hosting的安全规则,将后台页面放在your-project.web.app/dashboard路径下,仅允许认证用户访问:

  1. 配置Firebase Hosting重写规则
    修改firebase.json,确保单页应用路由正常工作,同时添加安全规则限制未认证用户访问/dashboard路径:

    {
      "hosting": {
        "public": "build",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ],
        "rewrites": [
          {
            "source": "/dashboard/**",
            "destination": "/index.html",
            "condition": {
              "auth": true
            }
          },
          {
            "source": "**",
            "destination": "/index.html"
          }
        ],
        "headers": [
          {
            "source": "/dashboard/**",
            "headers": [
              {
                "key": "Cache-Control",
                "value": "no-cache"
              }
            ]
          }
        ]
      }
    }
    

    这里的"auth": true条件会让Firebase Hosting自动拦截未认证用户,返回401错误。

  2. React应用添加路由守卫
    在React路由中添加认证检查,比如使用react-router-dom的Navigate组件:

    import { useEffect, useState } from 'react';
    import { Navigate, Outlet } from 'react-router-dom';
    import { getAuth, onAuthStateChanged } from 'firebase/auth';
    
    const ProtectedRoute = () => {
      const [isAuthenticated, setIsAuthenticated] = useState(null);
      const auth = getAuth();
    
      useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, (user) => {
          setIsAuthenticated(!!user);
        });
        return unsubscribe;
      }, [auth]);
    
      if (isAuthenticated === null) {
        return <div>加载中...</div>;
      }
    
      return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
    };
    
    // 在路由配置中使用
    <Route path="/dashboard" element={<ProtectedRoute />}>
      {/* 后台页面路由 */}
      <Route index element={<DashboardHome />} />
      <Route path="settings" element={<DashboardSettings />} />
    </Route>
    

    这样即使用户直接输入/dashboard路径,未登录时也会跳转到登录页,同时Firebase Hosting的规则也会在底层拦截未认证请求。

方案二:使用自定义域名的子域名(需自行购买域名)

如果你坚持要用子域名形式,需要购买自己的域名(比如yourdomain.com),然后在Firebase控制台添加dashboard.yourdomain.com作为自定义域名:

  • 购买域名后,在Firebase控制台的Hosting页面点击"添加自定义域名",输入dashboard.yourdomain.com。
  • 按照Firebase提供的DNS配置指引,在域名服务商处添加对应的CNAME或A记录。
  • 配置完成后,同样可以在firebase.json中添加auth: true的重写规则,限制仅认证用户访问该域名下的内容,同时在React应用中添加路由守卫。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:27:26