vue-router的history模式,跳转路由后出现404页面或者跳转到了网站首页。
今天来解决一个大家在做项目时遇到的常见问题。我们的路由一般都是用history路由模式,不仅链接美观,虽然hash路由模式也能实现,但是在公司网站地址携带一个"/#",这样看起来不是很正规。领导要求是能不用hash路由就不用。
Hash模式和History模式的区别

所以history模式的情况下,如果你不用跳转路由,就一个页面的情况下,可以不用另外配置服务器的路由规则。
那看看我的代码,我是vue3项目,使用vite和vue-router4。
router/index.js
import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/index.vue";
// 定义路由
const routes = [
{
path: "/",
redirect: "/index.html",
},
{
path: "/index.html",
name: "Home",
meta: { title: "活动页面" },
component: Home,
},
{
path: "/clock",
name: "clock",
meta: { title: "其他页面" },
component: () => import("../views/clock.vue"),
},
{
path: "/clock-detail",
name: "clock-detail",
meta: { title: "其他详情页面" },
component: () => import("../views/clock-detail.vue"),
}
];
// 创建路由实例并配置路由历史模式
const router = createRouter({
history: createWebHistory("/2025hd/"), // 子路径,例如你的项目要部署到 https://www.baidu.com/2025hd/
routes,
});
// 全局后置钩子,在路由切换完成后设置页面标题
router.afterEach((to) => {
if (to.meta.title) {
document.title = to.meta.title;
} else {
document.title = "活动页面";
}
});
router.beforeEach((to, from, next) => {
next();
});
export default router;
vite.config.js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
base: "./",
plugins: [vue()],
server: {
port: 3000, //端口
proxy: {
"/api": {
target: "xxxxxxx",
changeOrigin: true, //开启跨域
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
}
});
我的服务器是nginx,在nginx.conf 里面加上一条路由规则
server
{
## ...保留原有默认配置
## 新增这两条配置
location /2025hd/ { ## /2025hd/跟history路由地址一样,也要和部署路径一样
try_files $uri $uri/ /2025hd/index.html;
}
location / {
try_files $uri $uri/ /index.html; ##
}
}
配置好这些后重新打包上线,跳转路由再刷新页面,不会在出现404或者跳转到网站首页的问题啦~

被折叠的 条评论
为什么被折叠?



