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('/')
  }

如果有,注释或删除即可。

posted @ 2017-07-22 16:09  Liaofy  阅读(11307)  评论(0编辑  收藏  举报