vue项目部署到nginx/tomcat服务器

开发完的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打包
《vue项目部署到nginx/tomcat服务器》

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;
    }
}

运行结果:
《vue项目部署到nginx/tomcat服务器》

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的取值一致
《vue项目部署到nginx/tomcat服务器》

3)tomcat的配置
在tomcat的webapps新建文件夹,文件夹名称和上面配置的根路径一致,即为test,然后将打包生成的dist文件夹里面的文件复制到test下,并且新建文件WEB-INF/web.xml。
项目结构为:
《vue项目部署到nginx/tomcat服务器》
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
《vue项目部署到nginx/tomcat服务器》

    原文作者:Jello
    原文地址: https://segmentfault.com/a/1190000020187605
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞