同一域名部署 PC + H5,改 Nginx 的 root 后 H5 404?原因和完整配置

3 阅读2分钟

适用场景:宝塔 / 自建 Nginx,一个端口同时提供 PC 管理端(/)和 H5 采集端(/h5/),静态资源分目录存放。

现象

目录整理后,服务器结构如下:

/www/wwwroot/cstj/

├── yudao-server.jar

├── backup/

├── pc/ # PC 管理端

│ └── index.html

└── h5/ # H5 采集端

└── index.html

Nginx 把站点根改成了:

root /www/wwwroot/cstj/pc;

结果:

  • http://IP:3003/ → PC 正常
  • http://IP:3003/h5/ → 404 Not Found(nginx 返回)

浏览器控制台:

GET http://IP:3003/h5/ 404 (Not Found)

原因

root 只定义网站根目录。请求 /h5/ 时,Nginx 查找的是:

root + /h5/ → /www/wwwroot/cstj/pc/h5/index.html ❌

H5 实际文件在:

/www/wwwroot/cstj/h5/index.html ✅

结论:PC 挪进 pc/ 子目录后,不能只改一个全局 root,必须为 /h5/ 单独配置 location

路径与反代对照

访问路径物理目录 / 目标说明
//www/wwwroot/cstj/pcPC 管理端
/h5//www/wwwroot/cstj/h5H5 采集端
/admin-api/反代 127.0.0.1:48080PC 后端 API
/app-api/反代 127.0.0.1:48080H5 后端 API

推荐配置

顺序很重要: API 反代 → H5 / PC 的 location → 静态资源缓存正则。

server {

listen 3003;

server_name 106.53.175.247; # 改成你的域名或 IP

index index.html;

① 后端 API(必须在静态正则 location 之前)

location /admin-api/ {

proxy_pass http://127.0.0.1:48080/admin-api/;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Forwarded-Proto $scheme;

}

location /app-api/ {

proxy_pass http://127.0.0.1:48080/app-api/;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Forwarded-Proto $scheme;

}

② H5:子路径 /h5/ → 独立目录(用 alias,不要用 root)

location ^~ /h5/ {

alias /www/wwwroot/cstj/h5/;

index index.html;

try_files uriuri uri/ /h5/index.html;

}

③ PC:站点根 /

location / {

root /www/wwwroot/cstj/pc;

index index.html;

try_files uriuri uri/ /index.html;

}

④ 静态资源缓存(放最后)

location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {

expires 30d;

access_log off;

}

location ~ .*.(js|css)?$ {

expires 12h;

access_log off;

}

}

两个细节

  1. PC 用 root,H5 用 alias
  • root:URI = 根路径 + 请求路径 → / 对应 pc/index.html
  • alias/h5/xxx 映射到 h5/xxx,不会变成 h5/h5/xxx

2. ^~ /h5/

优先匹配 H5,避免被后面的 .(js|css)$ 等正则规则干扰。

部署后自检

文件是否存在

ls -la /www/wwwroot/cstj/pc/index.html

ls -la /www/wwwroot/cstj/h5/index.html

配置语法

nginx -t

重载

nginx -s reload

浏览器验证:

URL预期
http://IP:3003/PC 登录页
http://IP:3003/h5/H5 首页
F12 → Network接口走 /app-api/,静态资源在 /h5/assets/...

常见坑

现象原因处理
/h5/ 404只改了 root,未配 location /h5/按上文加 alias
H5 白屏、资源 404alias 末尾少 / 或目录未部署检查路径,重新上传 h5/
接口 404缺少 /app-api/ 反代补全 proxy_pass
改完仍 404伪静态 / rewrite 覆盖检查 include rewrite/*.conf

小结

  1. root 指向 pc/ 后,不会自动找到同级的 h5/ 目录。
  2. /h5/ 必须单独 locationalias 到 /www/wwwroot/cstj/h5/
  3. /admin-api//app-api/ 反代要保留,且写在静态正则 location 之前。

按此配置,同一域名、同一端口下 PC 与 H5 可同时对外服务。

标签: Nginx 前端 Vue 部署 404 宝塔