开发项目的时候,我们一般都会使用路由,但是使用hash路由还是history路由成为了两种选择,因为hash路由在url中带有#号,history没有带#号,看起来更加自然美观。但是hash速度更快而且更通用,history需要配置很多地方,浏览器兼容性也不是很好。但是领导要求要不带#号的history模式,那就只能满足他了。而且还需要在子路径下面开发和部署,所以就需要配置vite的base: '/h5',但是很奇怪的是配置了之后,本地打开竟然是一个空白页面,啥都没有啊,而且也没有报错!!!!什么报错都没有啊啊啊啊啊啊

这就搞笑了,没有报错怎么找问题?
但是使用createWebHashHistory模式就可以了:

所以怀疑还是路由这里出现问题了!
果然啊啊啊啊啊啊啊啊啊
这个路由createWebHistory模式就有一个隐藏的参数啊啊啊啊:

如果你的base地址配置为子路径或者啥的,就需要也在 createWebHistory中添加参数:

然后本地再次打开,就可以了:

部署到服务端
然后就是打包部署到服务端看看了,将项目部署到www目录下面的h5文件夹下:

然后需要配置nginx:注意root配置为/var/www/就可以了,不要加h5

然后nginx测试配置和重新加载配置:
nginx -t
sudo nginx -s reload
这个时候访问首页是ok的:

但是子页面就404了。。。。。。。。。

解决部署404问题
如果直接访问子页面(如 /h5/about),服务器会尝试查找 /var/www/h5/about 文件或目录,但实际 Vue 应用是一个单页应用(SPA),只有一个入口文件 index.html。由于服务器找不到对应的文件或目录,因此返回 404 错误。
解决方法
需要在 Nginx 配置中添加一个规则,将所有非静态资源的请求重定向到 index.html
,由 Vue Router 处理路由。
修改 Nginx 配置,将以下配置添加到你的 Nginx 配置中:
location /h5 {
root /var/www/;
index index.html index.htm;
try_files $uri $uri/ /h5/index.html;
}
解释:
root /var/www/;:指定根目录为 /var/www/,因此 /h5 对应的物理路径是 /var/www/h5。
index index.html index.htm;:指定默认的索引文件。
try_files $uri $uri/ /h5/index.html;:
首先尝试访问请求的文件(如 /h5/about)。
如果文件不存在,尝试访问目录(如 /h5/about/)。
如果仍然不存在,则将请求重定向到 /h5/index.html,由 Vue Router 处理路由。
然后nginx测试配置和重新加载配置:
nginx -t
sudo nginx -s reload
确保 Vue 项目的 base 配置正确
在 vite.config.js 中,确保 base 设置为 /h5/:

在 Vue Router 中,确保 history 的 base 也设置为 /h5/:

重启nginx之后,就可以访问子页面了:
