狙击手僵尸3D
191.56MB · 2025-12-08
这个原因的本质是 history 和 hash 的区别
以 www.louhc.com/jichu/123 为例子(123为变量)
直观上的区别是:
hash模式下,在浏览器地址栏里面会有: www.louhc.com/#/jichu/123 这种带 # 号的情况,视觉上不太美观。
history模式下,地址栏为:www.louhc.com/jichu/123 不会出现带#的情况 。
致命区别
hash模式下,上线之后不会出现问题。
history 模式下,会出现一个致命的BUG,在服务器上面上线之后,点击页面跳转没有问题,但是一旦点击刷新页面会出现404错误,原因是history模式下刷新界面,就等同于向服务器直接请求: www.louhc.com/jichu/123。但是在服务器后端的路径配置中压根就没有 /jichu/123 ,所以后端匹配不到相应的值,就会返回404错误,。有的朋友就会有疑虑,为什么在vue项目开发的时候不会出现这种问题呢?因为在vue项目开发的时候是访问自己的8080服务器,后端有进行处理,在刷新界面后找不到相对路径时,会重新渲染index.html界面,把路由的控制权交给前端,然后前端负责路由的匹配,在找到符合/jichu /123 这种格式的路由后,就会匹配成功。从而达到页面正常显示的情况.。
所以在线上遇到这种情况下,我们需要后端进行相应的配置处理,在匹配不到路径的情况下重新渲染index.html 文件。
以下是后端如何匹配的例子:
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 = 80http.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进行表达
对于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>
警告
需要注意的是:您的服务器将不再报告404错误,因为所有未找到的路径现在都可以处理您的index.html文件。要解决此问题,您应该在Vue应用程序中实施一个包罗万象的路由以显示404页面:
const router = new VueRouter({ mode: 'history', routes: [ { path: '*', component: NotFoundComponent } ]})
或者,如果您使用的是Node.js服务器,则可以通过使用服务器端的路由器来匹配输入URL来实现后备,如果没有路由匹配,则以404进行响应。查看Vue服务器端渲染文档以获取更多信息。