六、在Nginx非根目录下配置同域名多个子项目(Vite2+Vue3)
原创大约 3 分钟约 1027 字
前言
近期把公司内部管理系统从 Vue2 升级到 Vue3 版本,部署时遇到非根目录配置问题,需要在同一个域名的不同目录下配置两个网站,借此做个记录。
参考链接
- Vite 官网打包配置:共享配置 | Vite 官方中文文档
- Vue-Router4 配置:API 参考 | Vue Router
- Nginx 配置:Sticky Note | Vite 项目打包部署 Nginx 的一些 Issue - 掘金
- ruoyi-vue 部署在 nginx 非根目录刷新 404(已解决)_weixin_42554373 的博客-CSDN 博客_nginx 部署 ruoyi
- vue 项目使用 history 模式,打包部署到服务器根目录与二级目录的方法,防止刷新后出错_A 黄俊辉 A 的博客-CSDN 博客_vue 打包 history 模式
- 一文理清 nginx 中的 location 配置(系列一) - SegmentFault 思否
实现效果
- 访问
https://www.test.com/
:- 登录原 Vue2 项目网站,不影响路由跳转,无页面刷新 404 问题;
- 访问
https://www.test.com/vue3/
:- 登录新 Vue3 项目网站,不影响路由跳转,无页面刷新 404 问题。
(一)前端配置
1.修改路由配置文件,使用 HTML5 历史记录模式
// src/router/index.js
import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
history: createWebHistory("/vue3/"), // 注意前后都要有/
routes,
});
export default router;
2.修改 vite 配置文件
// vite.config.js
export default defineConfig({
build: {
chunkSizeWarningLimit: 1600, // 解决项目文件过大打包时的警告,可选
},
base: "/vue3/", // 关键代码
});
3.打包项目,生成/dist 目录
npm run build
4.上传项目文件到服务器目录
- 该步骤其实就是部署前端项目到服务器上。
- 将打包后的
/dist
目录下的内容上传到服务器相应目录即可。
目录路径根据自己项目确定,如下以我的项目为例:
- 原 Vue2 项目目录:
/data/wwwroot/admin
- 新 Vue3 项目目录:
/data/wwwroot/adminvue3
我的项目是在上述目录 git pull
拉取整个项目代码,所以配置 Nginx 时需要精确定位到 /dist
目录,如:
/data/wwwroot/admin/dist
/data/wwwroot/adminvue3/dist
如果服务器目录只包含 /dist
目录下的内容,则配置 Nginx 时定位到服务器文件夹目录即可,如:
/data/wwwroot/admin
/data/wwwroot/adminvue3
(二)Nginx 配置
1.修改 Nginx 配置文件
# Nginx配置文件所在目录
cd /usr/local/nginx/conf/vhost
# Nginx配置文件名称
vim www.test.com.conf
# 按 i 进行编辑模式
# 按 esc 退出编辑
# 编辑完成后按 :q 退出当前配置文件
# 按 :wq 保存当前修改并退出当前配置文件
2.原 Vue2 项目配置(域名下只有一个项目)
server {
listen 80;
listen [::]:80;
......
server_name www.test.com;
index index.html index.htm index.php;
root /data/wwwroot/admin/dist;
location / {
root /data/wwwroot/admin/dist;
try_files $uri $uri/ /index.html;
}
......
}
3.部署 Vue3 项目后的配置内容(同域名下有多个项目)
server {
listen 80;
listen [::]:80;
......
server_name www.test.com;
index index.html index.htm index.php;
root /data/wwwroot/admin/dist;
location / {
root /data/wwwroot/admin/dist;
try_files $uri $uri/ /index.html;
}
location ^~/vue3 {
alias /data/wwwroot/adminvue3/dist;
try_files $uri $uri/ /vue3/index.html;
}
......
}
4.关键代码解析
在我的项目中两种写法没有区别。
1)写法一
location ^~/vue3 {
alias /data/wwwroot/adminvue3/dist;
try_files $uri $uri/ /vue3/index.html;
}
2)写法二
location ^~/vue3 {
alias /data/wwwroot/adminvue3/dist;
try_files $uri $uri/ @router;
}
location @router {
rewrite ^/(vue3)/(.+)$ /$1/index.html last;
}
3)注意
location
要写^~/vue3
,写/vue3
页面会一直空白,并报错找不到assets
目录下的资源文件。(这个坑卡了一整天=-=||- 参考 location 配置:一文理清 nginx 中的 location 配置(系列一) - SegmentFault 思否
因为原 Vue2 项目的 location 是
/
,/vue3
会匹配到原 Vue2 项目,且原项目中没有/vue3
这个路由,所以页面空白,即没有资源文件。
^~/vue3
表示忽略其他 location 配置的 URI,直接匹配/vue3
,所以成功。
(三)重启 Nginx,完成部署
# 测试配置文件修改后是否有错
nginx -t
# 重启Nginx服务器
nginx -s reload