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

2022-10-16,,,,

开发完的vue项目,需要部署到nginx/tomcat服务器上运行,作为一个前端小白,刚接触vue不久,研究了一番,于是写下这篇文章,记录下来便于今后部署。

1.router(history)模式vue项目部署到nginx

1)修改router模式为history(默认为hash)

const router = new vuerouter({
 routes,
 mode: 'history'
});

对路由模式不清楚的小伙伴,可以看这篇

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《vue项目部署到nginx/tomcat服务器的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。