一.Vue项目部署在Nginx下
(一) 端口根路径下部署
1. Vue部署文件打包
终端执行
npm run build
打包部署文件,直接报文件扔到服务器正确位置即可
2. Nginx配置
#网页配置
#root为根路径方式部署vue项目
location / {
#vue项目的打包后的dist文件路径
root D:\projects\HIS-GDFY-MP\dist;
index index.html index.htm;
#需要指向下面的@router,否则会出现vue的路由在Nginx中刷新出现404
try_files $uri $uri/ @router;
}
#对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
#因此需要rewrite到index.html中,然后交给路由再处理请求资源
location @router {
rewrite ^.*$ /index.html last;
}
(二) 端口子路径下部署
1. Vue部署文件打包(vue-cli3.x)
(1)修改vue-config.js文件配置
module.exports = {publicPath: ""};
(2)修改路由route/index
const router = new Router({
base: '/hisGYFY/', //路由模式为history模式时,base必须要加上;路由模式为hash模式时,base可加可不加
mode: 'history',
routes: []
}
(3)终端执行
npm run build
打包部署文件
2. Nginx配置
#网页配置:子目录部署
location ^~ /hisGYFY {
#alias 表示非根路径
alias D:\projects\HIS-GDFY-MP\dist;
index index.html index.htm;
try_files $uri $uri/ /hisGYFY/@router;
}
location @router {
rewrite ^.*$ /index.html last;
}
(三) 反向代理解决跨域
1. 不改变源
location /hisfy/ {
proxy_pass http://ip:12080/hisfy/;
}
2. 改变源
(1)方式一
location /api {
proxy_pass http://ip:12080;
#可选参数,正则验证地址, 重写请求路径,遇到api,遇到/api,就将/api及前端的路径替换成代理的地址
rewrite ^.+api/?(.*)$ /$1 break;
}
(2)方式二
location /api {
# 路径后面加斜杆(/),可以代替方式一的重新rewrite语句
proxy_pass http://ip:12080/;
}