首页 > 建站教程 > 前端框架 >  vue-router history路由每次刷新,会在url后加上'/'导致403正文

vue-router history路由每次刷新,会在url后加上'/'导致403

vue-router history路由,部署后,每次刷新,会在url后面自动加上'/',导致403。

刷新前:

vue-router刷新403


刷新后:

vue-router刷新403


很奇怪,别的路由刷新页面没问题,就是这个路由有问题。原因是在项目目录下,有个同路由同名的文件夹,nginx匹配到了这个文件,同时这个文件夹下并没有index.html,就报这个错了:

vue-router刷新403


我们都知道,history路由,必须配置一段话,否则刷新会变成404:

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


或者简写:

location / {
  try_files $uri $uri/ /index.html;
}


这么配置的确不会变成404了,但是如果你的项目文件夹和路由同名,就会匹配到第二个规则“$uri/”,会在路由后面加上'/',导致403,这时候,尝试将第二个参数“$uri/”去掉试试,或者将路由改个名字,不要与项目文件夹同名,或者将项目下同名的文件夹重新命名都可以:

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

或者简写:

location / {
  try_files $uri /index.html;
}

此时刷新就没问题了。