1 问题描述
最近使用vue3的vite构建了一个新项目,在本地测试时是好好的没有什么问题,但是一发到服务器上刷新页面就会出现404,这样肯定会导致用户体验非常不好,于是我开始翻阅资料,找到几种处理方法
2 原因分析
出现这种情况应该是页面刷新没有找到根路径导致的
3 处理方法
3.1 方法一 使用webHashHsitory
修改router
文件夹下的index
配置文件,将history
方式改为createWebHashHistory
;因为hash方式的页面地址在刷新时只会刷新#
后面的内容,前面会保持不变
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
// 引入正式环境的打包路径
history: createWebHashHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
]
})
export default router
3.2 方法二 修改配置文件
因为我的项目需求,无法使用hash
的方式来解决这个问题,于是只能依然采用H5的history
方式
-
首先在
.env.production
配置文件中配置打包后的起始路径(一般默认路径是/
可以根据自己的需求配置不同的起始路径)# 资源访问路径 VITE_BASE_PUBLIC_PATH = "/page/hr"
-
在
vite.config.ts
文件中加载打包路径import { fileURLToPath, URL } from "node:url"; import { defineConfig, loadEnv } from "vite"; import vue from "@vitejs/plugin-vue"; import { ConfigEnv } from "vite"; import path from "node:path"; // https://vitejs.dev/config/ export default ({ mode }: ConfigEnv) => { // 获取当前环境的资源访问路径 const basePublicPath: string = loadEnv( mode, process.cwd() ).VITE_BASE_PUBLIC_PATH; return defineConfig({ base: basePublicPath, // 加载打包路径 plugins: [ vue(), ], resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)), }, }, }); };
-
修改服务器上的
nginx.conf
文件# HR页面 location /page/hr{ alias /page/ez_hr/; index index.html; # 重点 设置刷新的起始路径,避免出现找不到根路径从而404的问题 try_files $uri $uri/ /page/hr/index.html; }
-
最后也是最重要的一步,重启
nginx
服务!!直接热启动不一定生效(反正我的没生效)
3.3 升级版本(待验证)
- 我在stackflow上看到一个说法是
vite
打包本来就有这个问题,但是在5.0.0-beta.0
这个版本中问题已经修复了,但我用第二种方式已经解决了,这个就没试,有兴趣的朋友可以试一试