https://www.cnblogs.com/goloving/p/9170508.html
問題背景:
vue-router 默認是hash模式,使用url的hash來模擬一個完整的url,當url改變的時候,頁面不會重新加載。但是如果我們不想hash這種以#號結尾的路徑時候的話,我們可以使用路由的history的模式。比如如下網址:使用hash模式的話,那么訪問變成 http://localhost:8080/bank/page/count/#/ 這樣的訪問,如果路由使用 history的話,那么訪問的路徑變成 如下:http://localhost:8080/bank/page/count 這樣的了;
不過history的這種模式需要后台配置支持。比如:當我們進行項目的主頁的時候,一切正常,可以訪問,但是當我們刷新頁面或者直接訪問路徑的時候就會返回404,那是因為在history模式下,只是動態的通過js操作window.history來改變瀏覽器地址欄里的路徑,並沒有發起http請求,但是當我直接在瀏覽器里輸入這個地址的時候,就一定要對服務器發起http請求,但是這個目標在服務器上又不存在,所以會返回404
怎么解決呢?我們現在可以把所有請求都轉發到 http://localhost:8080/bank/page/index.html上就可以了。
解決方案:
對於VUE的router[mode: history]模式在開發的時候,一般都不出問題。是因為開發時用的服務器為node,Dev環境中自然已配置好了。
但對於放到nginx下運行的時候,自然還會有其他注意的地方。總結如下:
在nginx里配置了以下配置后, 可能首頁沒有問題,但鏈接其他會出現(404)
location / { root D:\Test\exprice\dist; index index.html index.htm; try_files $uri $uri/ /index.html; add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } location ^~/api/ { proxy_pass http://39.105.109.245:8080/; }
為了解決404,需要通過以下兩種方式:
1、官網推薦
location / { root D:\Test\exprice\dist; index index.html index.htm; try_files $uri $uri/ /index.html;
2、匹配errpr_page
location /{ root /data/nginx/html; index index.html index.htm; error_page 404 /index.html; }