vue-router
默認 hash 模式 —— 使用 URL 的 hash 來模擬一個完整的 URL墩剖,于是當 URL 改變時碎捺,頁面不會重新加載箱歧。
如果不想要很丑的 hash炎功,我們可以用路由的 history 模式凤薛,這種模式充分利用 history.pushState
API 來完成 URL 跳轉而無須重新加載頁面姓建。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
當你使用 history 模式時,URL 就像正常的 url枉侧,例如 http://yoursite.com/user/id
引瀑,也好看!
不過這種模式要玩好榨馁,還需要后臺配置支持憨栽。因為我們的應用是個單頁客戶端應用,如果后臺沒有正確的配置翼虫,當用戶在瀏覽器直接訪問 http://oursite.com/user/id
就會返回 404屑柔,這就不好看了。
所以呢珍剑,你要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態(tài)資源掸宛,則應該返回同一個 index.html
頁面,這個頁面就是你 app 依賴的頁面招拙。
后端配置例子
Apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
除了 mod_rewrite
唧瘾,你也可以使用 FallbackResource
措译。
nginx
location / {
try_files $uri $uri/ /index.html;
}
原生 Node.js
const http = require('http')
const fs = require('fs')
const httpPort = 80
http.createServer((req, res) => {
fs.readFile('index.htm', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.htm" file.')
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})
res.end(content)
})
}).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})
基于 Node.js 的 Express
對于 Node.js/Express,請考慮使用 connect-history-api-fallback 中間件饰序。
Internet Information Services (IIS)
- 安裝 IIS UrlRewrite
- 在你的網(wǎng)站根目錄中創(chuàng)建一個
web.config
文件领虹,內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Handle History Mode and custom 404/500" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Caddy
rewrite {
regexp .*
to {path} /
}
Firebase 主機
在你的 firebase.json
中加入:
{
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
警告
給個警告,因為這么做以后求豫,你的服務器就不再返回 404 錯誤頁面塌衰,因為對于所有路徑都會返回 index.html
文件。為了避免這種情況蝠嘉,你應該在 Vue 應用里面覆蓋所有的路由情況最疆,然后在給出一個 404 頁面。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
或者蚤告,如果你使用 Node.js 服務器努酸,你可以用服務端路由匹配到來的 URL,并在沒有匹配到路由的時候返回 404罩缴,以實現(xiàn)回退蚊逢。更多詳情請查閱 Vue 服務端渲染文檔。