部署项目到子目录

通常情况下,我们建议将程序部署到根目录下面,使用二级域名进行系统的访问
如:https://exam.yfhl.netopen in new window
但对于一些方案集成商或者需要共享会话等原因,需要将系统部署在子目录下面访
如:https://www.yfhl.net/examopen in new window
此时需要我们针对前端打包和服务器Nginx进行相应的配置即可实现,本文演示将考试系统部署到exam的二级目录中

PC前端配置

配置思路,将所有静态资源、路由、包括接口访问全部都增加二级目录/exam/

配置方式

只需修改环境变量文件中的 VITE_APP_BASE 即可。

根目录部署(默认)

# .env.production
VITE_APP_BASE =

留空表示部署在网站根目录,如 https://example.com/

二级目录部署

# .env.production
VITE_APP_BASE = /exam/

构建后 dist/ 目录下的所有静态资源将自动加上 /exam/ 前缀,部署时将 dist/ 内容放到服务器 /exam/ 路径下即可。

开发环境验证

.env.development 中同样支持 VITE_APP_BASE,配置后 npm run dev 启动即可在对应路径下测试:

# .env.development
VITE_APP_BASE = /exam/

运行 npm run dev,访问 http://localhost:5173/exam/ 即可验证。

移动端配置

H5 二级目录只看 manifest.json

"h5" : {
  "router" : {
    "base" : "/exam/",
    "mode" : "history"
  }
}
  • 部署到根目录时:base 配置为 /
  • 部署到 https://域名/exam/ 时:base 配置为 /exam/

这个配置会同时影响:

  • H5 路由基座
  • H5 静态资源基础路径
  • H5 内嵌页面资源路径,如 PDF viewer、直播播放器
  • H5 tabBar 图标路径修正

NGINX配置

前端文件我们已经增加了子目录访问,这个是没问题的;但是后台接口实际上是不需要二级目录的
正确接口地址为:http://localhost:8080/api/sys/config/detailopen in new window
现在请求地址为:http://localhost:8080/exam/api/sys/config/detailopen in new window
此时,我们在实际代理的时候,需要将/exam/去除,再转发到后端去处理


# 前端打包好的dist文件
set $dir '/data/run/sub/dist';

# 匹配手机端
if ($http_user_agent ~* (mobile|iphone|ipad|android|HarmonyOS)){
    set $dir '/data/run/sub/h5';
}

# 默认前端文件
location /exam/ {
  alias $dir/;
  try_files $uri $uri/ /index.html last;
}

# 后端接口
location ~/exam/(api/|upload/|druid/){
  rewrite ^/exam(/.*)$ $1 break;
  proxy_pass http://localhost:8080;
}

访问考试系统

配置好以后,使用完整的URL进行访问,如:https://www.yfhl.net/exam/pages/login/loginopen in new window

配置文件上传

以上配置我们将整个系统所有的访问URL都增加了/exam/目录,如果我们使用本地存储的话,在文件访问时也应当遵循此规则,如:

本地目录: /data/files/
访问URL: https://www.yfhl.net/exam/

如果您用的是其他云存储,则无需作此配置。

Last Updated:
Contributors: 沉醉寒风