vue react 路由history模式刷新404問題解決方案


vue單頁因微信分享和自動登錄需要,對於URL中存在’#’的地址,處理起來比較坑。用history模式就不會存在這樣的問題。但是換成history模式,就會有個新的問題,就是頁面刷新后,頁面就無法顯示了(404)。對於這個問題,我們只需要在服務器配置如果URL匹配不到任何靜態資源,就跳轉到默認的index.html。
我這里是針對nginx的配置,總結如下:
方案一 (這種方式容易被第三方劫持)

1 location /{
2         root   /data/nginx/html;
3         index  index.html index.htm;
4         error_page 404 /index.html;
5 }

方案二

1     location /{
2         root   /xxx/dist;
3         index  index.html index.htm;
4         if (!-e $request_filename) {
5             rewrite ^/(.*) /index.html last;    //    /index.html前面是有空格的 6             break;
7         }
8     }

方案三  vue.js官方教程里提到的https://router.vuejs.org/zh-cn/essentials/history-mode.html

 1   server {
 2         listen       8888;#默認端口是80,如果端口沒被占用可以不用修改
 3         server_name  localhost;
 4         root        /xxx/dist;#vue項目的打包后的dist
 5         location / {
 6             try_files $uri $uri/ @router;#需要指向下面的@router否則會出現vue的路由在nginx中刷新出現404
 7             index  index.html index.htm;
 8         }
 9         #對應上面的@router,主要原因是路由的路徑資源並不是一個真實的路徑,所以無法找到具體的文件
10         #因此需要rewrite到index.html中,然后交給路由在處理請求資源
11         location @router {
12             rewrite ^.*$ /index.html last;    /index.html前面有空格 13         }
14         #.......其他部分省略
15   }

配置詳解:

try_files 是指當用戶請求url資源時 www.xxx.com/xxx,try_files 會到硬盤資源根目錄里找 xxx。如果存在名為 xxx 的文件就返回,如果找不到在找名為 xxx 的目錄,再找不到就會執行@router。($uri指找文件, $uri/指找目錄)

rewrite是nginx中的重定向指令。^.*$ 是重定向規則。/index.html重定向路徑。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM