HTML5歷史記錄模式
雜湊模式的預設模式vue-router
是-使用URL雜湊來模擬完整的URL,以便在URL更改時不會重新載入頁面。
為了擺脫雜湊值,我們可以使用路由器的歷史記錄模式,它利用history.pushState
API來實現URL導航而無需重新載入頁面:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
使用歷史記錄模式時,URL看起來像“正常”,例如http://oursite.com/user/id
。美麗!
但是,這裡出現了一個問題:由於我們的應用程式是單頁客戶端應用程式,沒有正確的伺服器配置,因此如果使用者
http://oursite.com/user/id
直接在瀏覽器中訪問,他們將收到404錯誤。不必擔心:要解決此問題,您需要做的就是向伺服器新增一條簡單的“全部捕獲”後備路由。如果該網址與任何靜態資產均不匹配,則該網址應與index.html
您的應用程式所在的頁面相同。
伺服器配置示例
注意:以下示例假定您正在從根資料夾提供應用程式。如果部署到子資料夾,你應該使用的publicPath
Vue的CLI的選項和相關base
路由器的效能。您還需要調整下面的例子中使用的子資料夾,而不是根資料夾(如更換RewriteBase /
用RewriteBase /name-of-your-subfolder/
阿帕奇
<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.html', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.html" 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進行表達
對於Node.js / Express,請考慮使用connect-history-api-fallback中介軟體。
Internet資訊服務(IIS)
- 安裝IIS UrlRewrite
- 使用以下
web.config
命令在網站的根目錄中建立一個檔案:
<?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>
球童
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進行響應。檢視Vue伺服器端渲染文件以獲取更多資訊。