Vuejs+webpack部署子页面刷新404问题
使用vuejs+webpack在本地开发的时候很顺利,但在打包部署后子页面不能通过url地址直接访问到,只能通过主页点击前往各子页面。
router
vuejs的router默认使用的是hash,但是这种模式下的url看上去的体验很不好。因此改用history模式,在这种模式下的url看起来就会好很多,也符合平时的使用习惯。
在本地开发阶段并未发现问题,但在使用webpack打包部署后,出现了子页面不能直接通过url地址访问到的问题(也就是子页面刷新后会出现404)。
在查看官方文档后发现,虽然是一个单页面应用,但是需要对服务器进行适当的配置才可以。
解决办法
这个解决办法是来自vuejs的官方文档,经测试可以解决这个问题,所以当了一次搬运工,希望对大家有帮助。
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>
nginx
location / {
try_files $uri $uri/ /index.html;
}
Native 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)
})
Internet Information Services (IIS)
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>
Caddy
rewrite {
regexp .*
to {path} /
}
Firebase hosting
{
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
Caveat
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})