| 特性 | Hash 模式 | History 模式 |
|---|---|---|
| URL 表现 | example.com/#/home |
example.com/home |
| 原理 | 使用 URL 的 hash (#) 部分 |
使用 HTML5 History API |
| 是否发送请求 | hash 变化不发送请求 | 改变 URL 会发送请求 |
| 服务器要求 | 无特殊要求 | 需要服务器配置支持 |
// Hash 模式 (默认)
const router = new VueRouter({
mode: 'hash',
routes: [...]
})
// History 模式
const router = new VueRouter({
mode: 'history',
routes: [...]
})
history.pushState()项目无服务器控制权
兼容性要求高
简单项目/演示
需要 SEO 优化
追求更好的用户体验
#,更美观有服务器配置权限
Nginx:
location / {
try_files $uri $uri/ /index.html;
}
Apache (.htaccess):
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
Node.js (Express):
const history = require('connect-history-api-fallback')
app.use(history())
// 监听路由变化
window.addEventListener('hashchange', () => {
console.log('Hash changed:', window.location.hash)
})
// 手动修改 hash
window.location.hash = '/about'
// 编程式导航
router.push('/user') // → example.com/user
// 需要处理 404 问题
// 服务器需返回 index.html 让前端路由接管
开始选择路由模式
↓
是否需要 SEO? → 是 → 选择 History 模式
↓ ↓
否 能否配置服务器?
↓ ↓
是否需要支持旧浏览器? 是 → 采用 History 模式
↓ ↓
是 → 选择 Hash 模式 否 → 退回 Hash 模式
↓
部署到静态托管?
↓
是 → Hash 模式
↓
完成选择
// 根据环境自动选择
const mode = process.env.NODE_ENV === 'production'
? 'history'
: 'hash'
const router = new VueRouter({
mode,
routes: [...]
})
A: 配置服务器将所有路由重定向到 index.html
A: 不可以,但可以通过环境变量动态切换
| 维度 | Hash 模式 | History 模式 |
|---|---|---|
| URL 美观度 | 差(有 #) | 好 |
| SEO 支持 | 差 | 好(需配置) |
| 兼容性 | 完美 | IE10+ |
| 部署复杂度 | 简单 | 需服务器配置 |
| 服务器要求 | 无 | 需支持 SPA |
| 典型场景 | 后台系统、静态站点 | 官网、电商、需要 SEO 的站点 |
推荐原则:优先使用 History 模式,除非有明确的兼容性或部署限制。