带自定义basePath的NextJS项目NGINX热重载配置问题
同一域名下多NextJS项目(含自定义basePath)的NGINX热重载配置
核心问题原因
当NextJS项目设置了basePath: '/test'后,热重载的WebSocket请求路径会变为/test/_next/webpack-hmr,如果NGINX没有正确匹配并转发这个路径,就会导致WebSocket连接失败,热重载失效。
完整NGINX配置
server { listen 80; server_name your-domain.com; # 替换为你的实际域名 # 主项目:无basePath,运行在3000端口 location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } # 新项目:自定义basePath为/test,运行在3025端口 location /test { proxy_pass http://localhost:3025/test; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } # 单独处理新项目的热重载WebSocket请求 location /test/_next/webpack-hmr { proxy_pass http://localhost:3025/_next/webpack-hmr; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
配置说明
- 主项目转发:按官方标准配置处理WebSocket升级,确保无basePath的项目热重载正常。
- 新项目页面路由:
proxy_pass末尾必须加上/test,因为NextJS的basePath会让后端以这个前缀处理路由,否则会返回404。 - WebSocket路径匹配:新项目的WebSocket请求路径是
/test/_next/webpack-hmr,需要单独匹配该路径并转发到后端的/_next/webpack-hmr(后端内部的WebSocket路径不包含basePath前缀)。 - WebSocket必备头:所有涉及WebSocket的location块必须设置
proxy_http_version 1.1以及Upgrade、Connection请求头,这是实现WebSocket转发的核心条件。
验证步骤
- 确认新项目的
next.config.js中已配置:module.exports = { basePath: '/test' } - 执行
sudo nginx -s reload重载NGINX配置 - 打开浏览器控制台的「Network」标签,筛选「WS」类型,确认
/test/_next/webpack-hmr的请求状态为101 Switching Protocols,无报错。
内容的提问来源于stack exchange,提问作者Platon Podkopov
相关产品推荐
相关产品推荐

