vue-router/react-router使用History模式的nginx配置

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重定向路径。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容