目录
参考链接
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 思否
前言
近期把公司内部管理系统从Vue2升级到Vue3版本,部署时遇到非根目录配置问题,需要在同一个域名的不同目录下配置两个网站,借此做个记录。
实现效果
访问https://www.test.com/:登录原Vue2项目网站,不影响路由跳转,无页面刷新404问题;
访问https://www.test.com/vue3/:登录新Vue3项目网站,不影响路由跳转,无页面刷新404问题。
六、在Nginx非根目录下配置Vite2+Vue3项目
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.上传项目到服务器目录
该步骤根据自己项目确定,如下以我的项目为例:
原Vue2项目目录:/data/wwwroot/admin
新Vue3项目目录:/data/wwwroot/adminvue3
将打包后的/dist目录下的内容上传到上述目录即可。
(我的项目是在上述目录直接git pull整个项目,所以配置Nginx时需要定位到/dist目录)
5.修改Nginx配置文件
cd /usr/local/nginx/conf/vhost // Nginx配置文件所在目录
vim www.test.com.conf // Nginx配置文件名称
按i进行编辑模式
按esc退出编辑
:q退出当前配置文件
:wq保存当前修改并退出当前配置文件
1)原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;
}
......
}
2)部署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;
}
......
}
3)关键代码解析
location ^~/vue3 {
alias /data/wwwroot/adminvue3/dist;
try_files $uri $uri/ /vue3/index.html;
}
// 另一种写法,在我的项目中两种写法没区别
location ^~/vue3 {
alias /data/wwwroot/adminvue3/dist;
try_files $uri $uri/ @router;
}
location @router {
rewrite ^/(vue3)/(.+)$ /$1/index.html last;
}
location要写 ^~/vue3 ,写 /vue3 页面一直空白,并报错找不到assets目录下的资源文件,这个坑卡了一整天=-=||。
参考location配置:一文理清 nginx 中的 location 配置(系列一) - SegmentFault 思否
因为原Vue2项目的location是/,/vue3是匹配到原Vue2项目,且原项目中没有vue3这个路由,所以页面空白,没有资源文件,^~/vue3表示忽略其他URI,直接匹配/vue3,所以成功。
6.重启Nginx,完成部署
nginx -t
nginx -s reload