vue項目部署到nginx/tomcat服務(wù)器的實現(xiàn)
開發(fā)完的vue項目,需要部署到Nginx/Tomcat服務(wù)器上運行,作為一個前端小白,剛接觸vue不久,研究了一番,于是寫下這篇文章,記錄下來便于今后部署。
1.router(history)模式vue項目部署到nginx
1)修改router模式為history(默認為hash)
const router = new VueRouter({ routes, mode: 'history' });
對路由模式不清楚的小伙伴,可以看這篇vue-router路由模式詳解
2)修改config/index.js,build下靜態(tài)資源路徑,完成后執(zhí)行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; //項目存放的地址(當(dāng)前服務(wù)器位置) index /index.html; try_files $uri $uri/ @router; //一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態(tài)資源,返回同一個 index.html 頁面 } location @router { rewrite ^.*$ /index.html last; } }
運行結(jié)果:
2.vue項目部署到tomcat
1)項目上線,一般需要添加項目名,并且消去vue-router產(chǎn)生的#號,需要在router配置
const router = new VueRouter({ routes, mode: 'history', base: '/test/'//項目名稱 訪問路由頁面都需要加上這個,訪問的根路徑為http://ip:port/test });
2)修改config/index.js,build下靜態(tài)資源路徑與base的取值一致
3)tomcat的配置
在tomcat的webapps新建文件夾,文件夾名稱和上面配置的根路徑一致,即為test,然后將打包生成的dist文件夾里面的文件復(fù)制到test下,并且新建文件WEB-INF/web.xml。
項目結(jié)構(gòu)為:
WEB-INF目錄下新增web.xml內(nèi)容為:
//覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態(tài)資源,返回同一個 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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。