适用场景:宝塔 / 自建 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/pc | PC 管理端 |
/h5/ | /www/wwwroot/cstj/h5 | H5 采集端 |
/admin-api/ | 反代 127.0.0.1:48080 | PC 后端 API |
/app-api/ | 反代 127.0.0.1:48080 | H5 后端 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 uri/ /h5/index.html;
}
③ PC:站点根 /
location / {
root /www/wwwroot/cstj/pc;
index index.html;
try_files uri/ /index.html;
}
④ 静态资源缓存(放最后)
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {
expires 30d;
access_log off;
}
location ~ .*.(js|css)?$ {
expires 12h;
access_log off;
}
}
两个细节
- PC 用
root,H5 用alias
root:URI = 根路径 + 请求路径 →/对应pc/index.htmlalias:/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 白屏、资源 404 | alias 末尾少 / 或目录未部署 | 检查路径,重新上传 h5/ |
| 接口 404 | 缺少 /app-api/ 反代 | 补全 proxy_pass |
| 改完仍 404 | 伪静态 / rewrite 覆盖 | 检查 include rewrite/*.conf |
小结
root指向pc/后,不会自动找到同级的h5/目录。/h5/必须单独location,alias到/www/wwwroot/cstj/h5/。/admin-api/、/app-api/反代要保留,且写在静态正则location之前。
按此配置,同一域名、同一端口下 PC 与 H5 可同时对外服务。
标签: Nginx 前端 Vue 部署 404 宝塔