vue路由实现his
Vue 路由实现 History 模式
Vue Router 默认使用 hash 模式(URL 中的 #),但可以通过配置启用 HTML5 History 模式,消除 # 并保持单页应用特性。
启用 History 模式
在 Vue Router 配置中设置 mode: 'history':
const router = new VueRouter({
mode: 'history',
routes: [...]
})
服务器端配置
History 模式需要服务器支持,确保所有路由请求返回 index.html,否则刷新页面会导致 404。以下是常见服务器的配置示例:

Nginx
location / {
try_files $uri $uri/ /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>
Node.js (Express)
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
注意事项
- SEO 优化:History 模式对搜索引擎更友好,但需确保动态路由的 meta 信息正确。
- 404 处理:需在服务器和前端路由中定义 404 回退逻辑。
- 基础路径:若项目部署在子目录(如
/app/),需设置base选项:const router = new VueRouter({ mode: 'history', base: '/app/', routes: [...] })
前端路由守卫
History 模式下可通过导航守卫控制权限或重定向:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// 检查登录状态
next({ path: '/login' });
} else {
next();
}
});
通过以上配置和注意事项,可无缝实现 Vue Router 的 History 模式。






