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

如何在React中配置子域名路由?附现有路由代码

React子域名路由配置实现方案

要实现根据子域名(如admin.localhost:3000)跳转不同页面,React Router本身没有原生支持子域名匹配,需要手动解析当前域名并分情况渲染路由,具体步骤如下:

1. 编写子域名解析工具函数

先实现一个函数,从当前页面域名中提取子域名:

const getSubdomain = () => {
  const hostname = window.location.hostname;
  const parts = hostname.split('.');
  // 适配localhost本地开发场景
  if (hostname === 'localhost' || hostname.endsWith('.localhost')) {
    return parts.length > 1 ? parts[0] : '';
  }
  // 生产环境通用逻辑,可根据实际域名结构调整
  return parts.length > 2 ? parts[0] : '';
};

2. 修改路由组件,根据子域名渲染不同路由

在你的RoutePage组件中,先获取当前子域名,然后根据子域名判断渲染对应的路由结构:

import { BrowserRouter, Routes, Route } from 'react-router-dom';
// 导入所需组件:DefaultLayout、AdminLayout、MyInfo、AdminMyInfo等

export const RoutePage = () => {
  const subdomain = getSubdomain();

  return <BrowserRouter>
    <Routes>
      {/* admin子域名专属路由 */}
      {subdomain === 'admin' ? (
        <Route element={<AdminLayout />}>
          <Route path='/myinfo' element={<AdminMyInfo />} />
          {/* 可添加更多admin子域名下的路由 */}
          <Route path='*' element={<AdminNotFound />} />
        </Route>
      ) : (
        {/* 主域名原有路由 */}
        <Route element={<DefaultLayout />}>
          <Route path='/' element={<Main />} />
          <Route path='/login' element={<LoginPage />} />
          <Route path='/register' element={<RegisterPage />} />
          <Route path='/mypage' element={<MyPage />} />
          <Route path='/myinfo' element={<MyInfo />} />
          <Route path='*' element={<NotFoundPage />} />
        </Route>
      )}
    </Routes>
  </BrowserRouter>
};

3. 本地开发环境配置(关键)

本地直接访问admin.localhost:3000会无法解析,需要修改系统hosts文件:

  • Windows:C:\Windows\System32\drivers\etc\hosts
  • macOS/Linux:/etc/hosts

在文件末尾添加一行:

127.0.0.1 admin.localhost

保存后刷新DNS(Windows执行ipconfig /flushdns,macOS/Linux执行sudo dscacheutil -flushcache),即可正常访问admin.localhost:3000。

额外说明

  • 若需支持多个子域名,可扩展getSubdomain函数逻辑,或用switch-case处理不同子域名的路由规则。
  • 生产环境部署时,需确保服务器配置支持子域名解析(如Nginx配置server_name *.yourdomain.com)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:20:14