如何将Vue.js 2路由模式从hash改为history模式?
Vue 2.x 切换路由到history模式的正确方案
你用的是Vue 2.x,对应的是Vue Router 3.x版本,先明确两种写法的问题:
- 第二种写法里的
createRouter、createWebHistory是Vue Router 4.x(适配Vue3)的API,Vue2的路由库没有这些导出,所以触发了你看到的警告。 - 第一种写法是Vue Router 3.x的正确配置方式,但没生效的核心原因是生产环境服务器未配置history模式的重定向规则——history模式依赖服务器将所有路由请求转发到index.html,否则刷新页面会出现404。
正确操作步骤
配置Vue Router
保持你第一种写法的配置即可,这是Vue2的标准写法:import Vue from 'vue' import VueRouter from 'vue-router' import routes from './routes' Vue.use(VueRouter) const router = new VueRouter({ mode: 'history', // 开启history模式 routes: [...] }) export default router服务器端配置(必做)
开发环境下Vue CLI已经自动处理了路由重定向,所以开发时刷新页面没问题,但生产环境必须在服务器上添加规则:- Nginx:在站点配置中添加
try_files指令location / { try_files $uri $uri/ /index.html; } - 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> - Express:使用
connect-history-api-fallback中间件const express = require('express') const history = require('connect-history-api-fallback') const app = express() app.use(history()) app.use(express.static(__dirname + '/dist')) app.listen(3000)
- Nginx:在站点配置中添加
完成以上配置后,你的项目就能正常使用history模式了。
内容的提问来源于stack exchange,提问作者user16608259
相关产品推荐
相关产品推荐

