vue项目history路由,F5刷新页面,页面404问题,nginx try_files解决方案
有关history路由原理以及为什么刷新会404请查看往期文章
这里不再赘述为什么404的原因。
其实如果这么理解,可能会更加容易些。服务器会请求你所填写的真实地址,比如/about-us/where-to-go,会依次查找文件地址about-us、where-to-go,但是vue项目和普通项目不同,这只是路由,并不是真的文件目录地址,所有的路由都是依赖于SPA单页应用的index.html。所以当刷新时,找不到对应产生404。
所以我们需要使用nginx的try_files,去查找index.html.
nginx server配置
server {listen 9002;server_name localhost;gzip on;gzip_static on;gzip_proxied any;gzip_typestext/csstext/javascripttext/xmltext/plainimage/x-iconapplication/javascriptapplication/x-javascriptapplication/json;location / {add_header Cache-Control no-store;add_header Pragma no-cache;add_header Expires 0;root /home/test/;try_files $uri $uri/ @router;autoindex on;}location @router {rewrite ^.*$ /index.html last;}location ~ ^/(images) {add_header Cache-Control no-store;proxy_pass http://localhost:8990;}
}
try_files $uri $uri/ @router;
$uri 这个是nginx的变量,代表用户访问的单个文件地址。
比如:http://test.com/index.html, 那么$uri就是 /index.html。
$uri/ 这个代表用户访问的文件目录。
比如:http://test.com/index.html, 那么$uri就是 /index.html。
所以try_files $uri $uri/的意思就是,比如http://test.com/example先去查找单个文件example,如果example不存在,则去查找同名的文件目录/example/,如果再不存在,将进行重定向@router
rewrite [regex] [replacement] [flag];url正则表达式 替换成真实url 标记(last,break)location @router {rewrite ^.*$ /index.html last;# 匹配所有 /index.html last;
}
凡是404的路由,都会被重定向到index.html,这样就显示正确了
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
