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服务器端渲染文档以获取更多信息。