美文网首页
vue-router/react-router使用History

vue-router/react-router使用History

作者: 岁月如同马匹 | 来源:发表于2017-07-14 10:58 被阅读0次

vue-router 或者 react-router 路由模式有两种,一种是使用hash来控制视图的跳转。另一种是使用 history 模式,使用 history.pushState API 来控制视图的跳转。使用 hash 的缺点是路由的样子会是 #/a/b 这种样子,而且在微信分享时会出现问题。所以推荐使用history模式的路由。

使用history模式的服务端支持

由于使用history时的路由是 www.xxx.com/a/b/c ,url 是指向真实 url 的资源路径。因此回去服务端查询该资源。往往资源是不存在的于是就会报404。下面以 ngixn 为例修改 nginx 配置以支持history路由。

nginx 整体配置

原始配置

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location ~ ^/api {
        proxy_pass http://xxx.com:3000;
    }
    location / {
        root /xxx/dist;
        index  index.html index.htm;
    }

修改后的配置

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location ~ ^/api {
        proxy_pass http://xxx.com:3000;
    }
    location / {
        root /xxx/dist;
        index  index.html index.htm;
        try_files $uri $uri/ @rewrites;    
    }
    location @rewrites {
         rewrite ^(.+)$ /index.html last;
    }

配置详解

由修改看出nginx此次修改,主要增加了

    location / {
        try_files $uri $uri/ @rewrites;    
    }

try_files 是指当用户请求url资源时 www.xxx.com/xxx,try_files 会到硬盘资源根目录里找 xxx。如果存在名为 xxx 的文件就返回,如果找不到在找名为 xxx 的目录,再找不到就会执行@rewrites。($uri指找文件, $uri/指找目录)

    location @rewrites {
         rewrite ^(.+)$ /index.html last;
    }

rewrite是nginx中的重定向指令。^(.+)$ 是重定向规则。/index.html重定向路径。

相关文章

网友评论

      本文标题:vue-router/react-router使用History

      本文链接:https://www.haomeiwen.com/subject/rodnhxtx.html