今天receat build 打包一个项目的时候,正常输入index.html访问的时候没有问题,但是刷新后出现了404错误。调试的时候正常。
文件打包后生成index.html文件和dist目录。
首页进入后正常,xxxx/index.html,点击一个页面后url变为:xxxx/app
正常访问下访问其他页面是由component-route控制,但是刷新的时候这个路由文件并没有加载,因此会去寻找服务器端资源,没有找到就会返回404。
查找资料后,开启HTML5 History Mode后,需要server端的支持.
服务端重写url即可
Apache 伪静态 .htaccess文件
<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;
}
注意:
给个警告,因为这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回 index.html 文件。为了避免这种情况,你应该在Vue或react应用里面覆盖所有的路由情况,然后在给出一个 404 页面。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})