vue 项目 页面刷新404问题

vue页面访问正常,但是一刷新就会404的问题?

为什么会出现404?

我们打开dist文件夹,可以看到只有一个 index.html 文件及一些静态资源,这个是因为Vue是单页应用(SPA),只有一个index.html作为入口文件,其它的路由都是通过JS来进行跳转;

接着我们再来分析一下后端 nginx 的配置.

server {
  // 监听80端口
  listen 80;
  // 定义你的站点名称
  server_name website.com;
  // 根据请求 URI 设置配置
  location / {
      // 站点根目录,这里为 vue 构建出来的 dist 目录
      root   /www/dist;
      // 站点初始页为index.html 或 index.htm
      index  index.html index.htm;
  }
}

我们现在可以根据 nginx 配置得出,当我们在地址栏输入 website.com 时,这时会打开我们 dist 目录下的 index.html 文件,然后我们在跳转路由进入到 website.com/login;

关键在这里,当我们在 website.com/login 页执行刷新操作,nginx location 是没有相关配置的,所以就会出现 404 的情况.

解决办法

第一种解决方法

将vue路由模式mode: 'history' 修改为 mode: 'hash'

//router.js文件
const router = new Router({
    //mode: 'history', 
    mode: 'hash',
    routes: [
        { path: '/', redirect: '/login' },
        { path: '/login', component: Login },
    ]
})

为什么hash模式下没有问题?

router hash 模式我们都知道是用符号#表示的,如 website.com/#/login, hash 的值为 #/login;

它的特点在于:hash 虽然出现在 URL 中,但不会被包括在 HTTP 请求中,对服务端完全没有影响,因此改变 hash 不会重新加载页面;

hash 模式下,仅 hash 符号之前的内容会被包含在请求中,如 website.com/#/login 只有 website.com 会被包含在请求中 ,因此对于服务端来说,即使没有配置location,也不会返回404错误.

第二种解决方法

在服务器Nginx配置文件里,添加如下代码,再重启Nginx,刷新网页就OK了

location / {
 try_files $uri $uri/ @router;
  index index.html;
}
 
location @router {
  rewrite ^.*$ /index.html last;
}
posted @ 2022-08-09 16:55  槑孒  阅读(263)  评论(0编辑  收藏  举报