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

React.js多子域名配置求助:解决Invalid host header报错问题

在React中配置多子域名的解决方法

你遇到的Invalid host header错误,是因为React开发服务器默认会校验请求的Host头,未被纳入允许列表的域名会被拦截。以下是具体解决步骤:

1. 绑定本地子域名到localhost

先把自定义子域名指向本地IP(127.0.0.1),需要修改系统hosts文件:

  • Windows系统:打开C:\Windows\System32\drivers\etc\hosts(需管理员权限),添加一行:
    127.0.0.1 subdomain.localhost
    
  • Mac/Linux系统:打开终端执行命令编辑hosts文件:
    sudo nano /etc/hosts
    
    同样添加上述内容后,按Ctrl+O保存、Ctrl+X退出。

2. 配置React开发服务器允许子域名

根据你使用的React脚手架工具,选择对应配置方式:

若使用Create React App(CRA)

有两种简单配置方式:

  • 方式一:修改启动命令
    在项目package.json的scripts字段中,给start命令添加允许子域名的参数:
    "scripts": {
      "start": "react-scripts start --allowed-hosts .localhost",
      "build": "react-scripts build",
      "test": "react-scripts test"
    }
    
    这里的.localhost表示允许所有*.localhost格式的子域名。
  • 方式二:使用环境变量文件
    在项目根目录创建.env.development文件,添加以下内容:
    ALLOWED_HOSTS=.localhost
    

若使用Vite

在项目根目录的vite.config.js中修改服务器配置:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    host: '0.0.0.0',
    allowedHosts: ['.localhost']
  }
})

3. 验证配置

重启React开发服务器,访问subdomain.localhost:3000,此时应该能正常加载页面,不会再出现Invalid host header错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:01:17