本文將描述遇到的問題,並給出解決方案
一、遇到的問題
- 使用history模式,本地沒有問題。打包部署再nginx上會報錯404,找不到頁面。
- 部署二級域名或者說多級訪問的url,導致訪問失敗。(EG:http://www.baidu.com/baiduwangpan/aaaa)
二、解決方案
1、解決使用history模式,本地沒有問題。打包部署再nginx上會報錯404,找不到頁面。
由於本文重點介紹如何實現nginx配合history模式進行路由的正常訪問。故只貼出路由部分:(采用vue-router)
// 路由配置
export default new Router({ mode: 'history', base: '', routes: [ { path: '/', name: 'root', component: window.userAgent === 'pc' ? PcIndex : MobileIndex }, { path: '/moli', name: 'moli', component: window.userAgent === 'pc' ? PcIndex : MobileIndex }, { path: '/app', name: 'app', component: AppIndex } ] })
將項目進行打包,需要注意的是打包之前最好修改/config/index.js build模塊的 assetsPublicPath 將其改為:
因為打包后部署最好使用相對路徑,這樣即使項目不放在根目錄下,也不會有找不到靜態資源的情況。
接下來我們把打包好的代碼放到nginx下的目錄中(nginx 采用window版本的。下載教程和安裝不做具體描述,需要的自行搜索。)
再nginx下面創建一個test目錄用來存放我得項目
然后配置nginx,conf/nginx.conf
#test路徑 location / {
# 配置訪問目錄 root test/;
# 重點需要添加這句 try_files $uri $uri/ /index.html; index index.html login.html; }
demo演示
2、部署二級域名或者說多級訪問的url,導致訪問失敗。(EG:http://www.baidu.com/baiduwangpan/aaaa)
首先解釋下什么是二級域名,以上面為例我們訪問的路徑是 localhost/moli。假設我們需要訪問的路徑為:localhost/callcenter/moli localhost/callcenter/app
按照nginx原有的規則配置我們需要將訪問的localtion進行多級配置,如下:
location /callcenter { # 配置訪問目錄 root test/; # 重點需要添加這句 try_files $uri $uri/ /index.html; index index.html login.html; }
我們重啟nginx在瀏覽器中輸入 localhost/callcenter/moli 試一下,結果是找不到我們的項目,重定向到nginx默認的歡迎頁面
相信很多伙伴都會遇到這部分問題,這個問題真是應了那句話,會的人不覺得難,不會的人真是一點頭緒都沒有。對於一個前端來說這個問題困擾了我兩周左右。到底是如何解決得呢?
其實很簡單,首先我們要對vue的router進行一個補充,注意到的同學已經看見我實例化Router對象的時候里面有一個base屬性是空的,我們如果想要配置二級路徑就需要對應得將base屬性進行填寫。與想要訪問的路徑必須對應。
在這里我不多做vue-router 和 nginx router的原理解釋,有看不懂的同學直接留言,看見后我如果了解的話一定回復:
首先添加base基准路徑
// router
export default new Router({ mode: 'history', base: '/callcenter/', routes: [ { path: '/', name: 'root', component: window.userAgent === 'pc' ? PcIndex : MobileIndex }, { path: '/moli', name: 'moli', component: window.userAgent === 'pc' ? PcIndex : MobileIndex }, { path: '/app', name: 'app', component: AppIndex } ] })
其次需要創建需要在test目錄下創建callcenter目錄
最后配置nginx
#test路徑 location ^~ /callcenter/ { root test/; $uri $uri/ /callcenter/index.html; index.html login.html; }
nginx -s reload 重啟nginx后訪問 localhost/callcenter/moli
完美運行.......
vue官方對History模式的介紹:https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90
如有不足請指出,如有疑問歡迎留言