vue-router 或者 react-router 路由模式有兩種,一種是使用hash來(lái)控制視圖的跳轉(zhuǎn)。另一種是使用 history 模式,使用 history.pushState API 來(lái)控制視圖的跳轉(zhuǎn)。使用 hash 的缺點(diǎn)是路由的樣子會(huì)是 #/a/b 這種樣子,而且在微信分享時(shí)會(huì)出現(xiàn)問(wèn)題。所以推薦使用history模式的路由。
使用history模式的服務(wù)端支持
由于使用history時(shí)的路由是 www.xxx.com/a/b/c ,url 是指向真實(shí) url 的資源路徑。因此回去服務(wù)端查詢(xún)?cè)撡Y源。往往資源是不存在的于是就會(huì)報(bào)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 是指當(dāng)用戶(hù)請(qǐng)求url資源時(shí) www.xxx.com/xxx,try_files 會(huì)到硬盤(pán)資源根目錄里找 xxx。如果存在名為 xxx 的文件就返回,如果找不到在找名為 xxx 的目錄,再找不到就會(huì)執(zhí)行@rewrites。($uri指找文件, $uri/指找目錄)
location @rewrites {
rewrite ^(.+)$ /index.html last;
}
rewrite是nginx中的重定向指令。^(.+)$ 是重定向規(guī)則。/index.html重定向路徑。