history 路由404,nginx配置
# 前言
前端路由大致分为
hash
模式和history
模式两种,并且前端路由的主要实现思路其实就是路由改变而不重新像服务器请求资源。在这一点上hash路由可以很好的坐到。而history路由则就需要服务端同学做一些额外的配置支持一下了。具体的两种路由这里就不多做介绍。直接进入正文
# nginx配置
通常nginx
会为匹配不到的资源跳转到404兜底
,而history模式下刷新浏览器,浏览器会真实的像服务器去请求url
对应的资源,这个时候资源是不存在的,我们就需要给他都重定向到index.html
文件去。
server {
listen 80; #监听80端口
server_name xxx; #域名
#这里我们有三个项目都部署到了同一个域名下,所以对每个项目都进行一个配置
location /h5 {
root /mnt/belife-work/;
try_files $uri $uri/ /h5/index.html; #重点在这一句,路径要天你的站点对应的后缀下的inde.html
index index.html index.htm;
}
location /cms {
root /mnt/belife-work/;
index index.html index.htm;
}
location /admin {
root /mnt/belife-work/;
try_files $uri $uri/ /admin/index.html;
index index.html index.htm;
}
location ~ /v1/app { # 服务端接口代理
proxy_pass http://localhost:8081;
}
location ~ /v1/work {
proxy_pass http://localhost:8088;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
try_files $uri $uri/ /h5/index.html 重点代码,路径的话跟着你的站点后缀
自由变化就行,如果你是在根目录
下那就直接/index.html
即可
# 另外
如果你的站点不是部署在根目录
,而是像上文中的/h5
,/admin
目录下的话,那你的路由还需要配置一下base
属性,这样,vue-router会自动的帮你在路由前面加上前缀
。
注意:这里的base
和打包配置
里的base
可不一样哦,路由里的base
作用是在你的路由
里添加上前缀
,而vue.config.js
里的base
则是你构建后的静态资源
的前缀
,比如你的静态资源可能会放置在别的cdn上,那么vite会自动帮你加上cdn的前缀,也就是你配置的base,这样就无需手动的去添加了
编辑 (opens new window)
上次更新: 2023/05/08, 15:54:48