(nginx系列) 第三篇:vue刷新页面404问题(history模式)

hcwei 2020年06月10日 476次浏览

背景介绍

vue路由有两种模式hash模式和history模式,使用hash模式url中会有"#",不够美观,使用history则无此问题。但是对于使用history模式会出现刷新页面404的问题,可以通过nginx配置解决此问题。

  • 方法1:
location /{
    root   /var/www/html;
    index  index.html;
    if (!-e $request_filename) {
        rewrite ^/(.*) /index.html last;
        break;
    }
}

此方法使用if判断请求文件是否存在,不存在通过rewrite重写交给/index.html重新请求。

  • 方法2:
location / {
    # 需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
    try_files $uri $uri/ @router;
    index  index.html;
}
# 对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
# 因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
    rewrite ^.*$ /index.html last;
    }
}

此为vue官方的配置方法,通过try_files查找请求的文件,不存在交给@router处理,然后根据@router这个location处理请求。这种方法与方法1其实原理一样只是写法上略有不同。