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

Windows本地环境下如何让NextJS识别localhost子域名?

问题描述

我的Windows hosts文件配置如下:

  • 127.0.0.1 localhost
  • 127.0.0.1 subsite.localhost

在3001端口运行NextJS项目时,可通过以下地址访问:

  • http://localhost:3001
  • http://subsite.localhost:3001

但NextJS始终只识别主机名为localhost。使用middleware.js调试时得到以下结果:

  • NextRequest.nextUrl.host === localhost:3001
  • NextRequest.headers.get("host") === 127.0.0.1:38607

运行环境:Windows11 + Docker + WSL2,终端使用Ubuntu。

解决方法

1. 修改NextJS启动绑定地址

NextJS默认绑定localhost,会导致WSL2/Windows之间的域名请求被转成IP,丢失主机名。启动时指定绑定到0.0.0.0:

next dev -H 0.0.0.0 -p 3001

如果是用Docker运行,确保Dockerfile里的启动命令也加上-H 0.0.0.0。

2. 修正Docker端口映射配置

确保Docker容器的3001端口映射到0.0.0.0,而不是仅localhost,这样Windows侧的域名请求能正确传递主机头:

  • 命令行启动Docker时:
    docker run -p 0.0.0.0:3001:3001 [你的镜像名]
    
  • 使用docker-compose时,在ports字段配置:
    ports:
      - "0.0.0.0:3001:3001"
    

3. 同步WSL2内部hosts配置

WSL2有独立的网络栈,Windows的hosts不会自动同步到WSL2,需要在Ubuntu终端里编辑/etc/hosts,添加对应域名:

sudo nano /etc/hosts

添加一行:

127.0.0.1 subsite.localhost

保存退出后,WSL2内部就能正确解析该域名,避免请求被转换为IP。

4. 调整Middleware的主机名获取逻辑

由于Docker/WSL2的网络转发可能会修改host头,在middleware中优先读取x-forwarded-host头(如果存在),确保获取到正确的原始主机名:

import { NextResponse } from 'next/server'

export function middleware(request) {
  // 优先获取反向代理传递的原始主机名,再降级到其他方式
  const originalHost = request.headers.get('x-forwarded-host') 
    || request.headers.get('host') 
    || request.nextUrl.host
  console.log('原始主机名:', originalHost)
  // 后续业务逻辑
  return NextResponse.next()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:52:46