需求
将多个vue项目通过nginx部署到同一台服务器,通过ip:80/demo1
,ip:80/demo2
这种形式去访问
环境
- vue 3
- vue-router 4
- vue cli 4
最开始只是想要解决的是一个项目通过tomcat部署到服务器之后刷新报404的错误,官方也给出解决方案,通过nginx配置,好吧,尝试使用Nginx,结果遇到好多问题,各种404,403,500,这里给出最终成功的方案,关键参考:链接
项目一
vue.config.js
...
publicPath:"/position",
outputDir: "positionDist",
...
router/index.js
...
const router = createRouter({
//要和上面publicPath一致,以及注意斜杠
history: createWebHistory('/position/'),
// history: createWebHashHistory(),
routes: constantRoutes,
})
...
项目二
基本一样
vue.config.js
...
publicPath:"/mining",
outputDir: "miningDist",
...
router/index.js
...
const router = createRouter({
//要和上面publicPath一致,以及注意斜杠
history: createWebHistory('/mining/'),
// history: createWebHashHistory(),
routes: constantRoutes,
})
...
部署准备
npm run build 打包出positionDist,miningDist
放到服务器上,比如/opt/…,下面我的配置里可以看到是在tomcat下,其实完全不需要tomcat,随便放个文件夹就行
Nginx配置
user root;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
#这个匹配其实没用,不写又不行,三个项目都在下面
location / {
root /opt/tomcat/webapps/position;
index index.html;
try_files $uri $uri/ /index.html;
}
#项目一position
location /position {
#要用alias,地址是项目Dist文件的绝对路径
alias /opt/tomcat/webapps/positionDist;
index index.html;
#解决history模式下router,页面刷新404的错误,
#注意最后index.html是location后面跟的路径
#网上找到的对我这种新手不友好,包括vue官方给的
try_files $uri $uri/ /position/index.html;
}
#项目二mining
location /mining {
alias /opt/tomcat/webapps/miningDist;
index index.html;
try_files $uri $uri/ /mining/index.html;
}
#项目N...
location /lifter {
alias /opt/tomcat/webapps/lifterDist;
index index.html;
try_files $uri $uri/ /lifter/index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}