Vue 部署單頁應用,刷新頁面 404/502 報錯


在 Vue 項目中,可以選擇 hash或者 history.pushState() 實現路由跳轉。如果在路由中使用history模式:

export default new Router({
  mode: 'history',

  base: __dirname,
  scrollBehavior,
  routes: [index, blog, project, about, list]
})

那么,當我們 npm run build 完成並部署到服務器后,刷新某個路由下的頁面,會出現 404 或者 502 錯誤。

這是因為刷新頁面時訪問的資源在服務端找不到,因為vue-router設置的路徑不是真實存在的路徑。

解決方法

簡單配置下 nginx ,讓所有路由(url)下的頁面重寫到 index.html即可:


server {
        listen 80;
        server_name www.fayinme.cn;

        gzip on;
        gzip_min_length 1k;
        gzip_buffers 4 16k;
        gzip_comp_level 2;
        gzip_vary off;
        gzip_disabled "MSIE [1-6]";
        autoindex on;

        root /www/blogfront/production/current;
        index index.html;
        
        location / {
                try_files $uri $uri/ @router;
                index index.html;
        }

        location @router {
                rewrite ^.*$ /index.html last;
        }

注意

配置完成后,如果刷新任意頁面(F5)都跳轉到首頁,你需要查看下 app.vue 是否包含了如下代碼:

  created() {
    this.$router.push('/')
  }

如果有,注釋或刪除即可。


免責聲明!

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



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