vue-router 或者 react-router 路由模式有两种,一种是使用hash来控制视图的跳转。另外一种是使用 history 模式,使用 history.pushState API 来控制视图的跳转。使用 hash 的缺点是路由的样子会是 #/a/b 这种样子,并且在微信分享时会出现问题。因此推荐使用history模式的路由。html
因为使用history时的路由是 www.xxx.com/a/b/c ,url 是指向真实 url 的资源路径。所以回去服务端查询该资源。每每资源是不存在的因而就会报404。下面以 ngixn 为例修改 nginx 配置以支持history路由。vue
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这次修改,主要增长了react
location / {
try_files $uri $uri/ @rewrites;
}
复制代码
try_files 是指当用户请求url资源时 www.xxx.com/xxx,try_fil… 会到硬盘资源根目录里找 xxx。若是存在名为 xxx 的文件就返回,若是找不到在找名为 xxx 的目录,再找不到就会执行@rewrites。(uri/指找目录)nginx
location @rewrites {
rewrite ^(.+)$ /index.html last;
}
复制代码
rewrite是nginx中的重定向指令。^(.+)$ 是重定向规则。/index.html重定向路径。vue-router