 history 路由404,nginx配置
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