开发完的vue项目,需要部署到Nginx/Tomcat服务器上运行,作为一个前端小白,刚接触vue不久,研究了一番,于是写下这篇文章,记录下来便于今后部署。
1.router(history)模式vue项目部署到nginx
1)修改router模式为history(默认为hash)
const router = new VueRouter({
routes,
mode: 'history'
});
对路由模式不清楚的小伙伴,可以看这篇vue-router路由模式详解
2)修改config/index.js,build下静态资源路径,完成后执行npm run build打包
3)修改nginx配置
server {
listen 80;//代理端口
server_name 192.168.0.152;//代理名称(域名、ip)
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root test; //项目存放的地址(当前服务器位置)
index /index.html;
try_files $uri $uri/ @router; //一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,返回同一个 index.html 页面
}
location @router {
rewrite ^.*$ /index.html last;
}
}
运行结果:
2.vue项目部署到tomcat
1)项目上线,一般需要添加项目名,并且消去vue-router产生的#号,需要在router配置
const router = new VueRouter({
routes,
mode: 'history',
base: '/test/'//项目名称 访问路由页面都需要加上这个,访问的根路径为http://ip:port/test
});
2)修改config/index.js,build下静态资源路径与base的取值一致
3)tomcat的配置
在tomcat的webapps新建文件夹,文件夹名称和上面配置的根路径一致,即为test,然后将打包生成的dist文件夹里面的文件复制到test下,并且新建文件WEB-INF/web.xml。
项目结构为:
WEB-INF目录下新增web.xml内容为:
//覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,返回同一个 index.html页面
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true">
<display-name>Router for Tomcat</display-name>
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
</web-app>
详细了解可看vue官方文档后端配置HTML5 History 模式
4)重新启动tomcat
3.nginx部署多个vue项目
需要在同一域名端口下,部署两个项目
1)准备两个项目
2)vue-test不用修改配置,直接build,vue-admin需要修改下配置
修改config/index.js
build: {
...
assetsPublicPath: '/admin/',
...
}
修改router/index.js
const createRouter = () => new Router({
...
base: 'admin',
...
});
完成后重新build打包
3)修改nginx/conf/nginx.conf
server {
listen 9090;
server_name 192.168.0.153;
location / {
root vue-test;
try_files $uri $uri/ @router;
index index.html index.htm;
}
location /admin {//二级目录
alias vue-admin;
try_files $uri $uri/ /admin/index.html;
index index.html index.htm;
}
location @router {
rewrite ^.*$ /index.html last;
}
location /xxx {//跨域代理
add_header 'Access-Control-Allow-Origin' '*';
proxy_pass http://ip:port/xxx;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
重新加载nginx配置 nginx -s reload
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。