Vue项目上传nginx出现前端资源和api路由冲突?-灵析社区

开挂思想家

yarn vue3项目打包后将dist根目录上传nginx web根目录,[http://aaa.com/index.html](https://link.segmentfault.com/?enc=aQCadgRo%2Bh54%2BMtrENKKtA%3D%3D.DvuFyyjLYkhE7ARSSPs%2BPXCo0ySZF6ZFTKW521Pc5Ps%3D) 这个index.html就是dist生成的,我没有上传dist这个文件夹,直接把里面的静态文件上传web根目录。 第一次请求后,会跳转到aaa.com/login进行登录,登录完成进入aaa.com/home显示正常 但是将aaa.com/home刷新就会显示404,我在nginx配置添加:try_files $uri $uri/ /index.html; 然后正常,但是刷新后不断请求api接口,F12请求上百次 我手动访问api接口: aaa.com/admin/getadmin, aaa.com/api/getuser, aaa.com/index/getmenu, 这三个api全部是前端展示的,并没有走vue 代理 如果不添加nginx配置 try_files $uri $uri/ /index.html; 访问全部正常如下: { "code": 401, "msg": "登录不合法" } 也就是说访问首页404和api接口冲突,请问这个如何解决?感谢路过的大佬!!! 我使用的是Vue createWebHistory模式

阅读量:108

点赞量:0

问AI
可以贴一下配置文件。。 这个 "location" 是有优先级的,根据规则来匹配判断选择不同的配置。 当匹配到 location / 时,就会走try_files,这里 try_files 就是判断 $uri 这个路径在nginx服务器上是不是存在的,如果不存在判断下一个,一直到 /index.html。 很明显这里 所有的请求都被匹配到 try_files 了,所以后端的接口才会一直返回前端的index.html(前端页面)。 解决方法就是在加一个优先级更高的 location ,让接口的请求走代理。 举个例子: server { listen 80; server_name domain.com; root /data/www/test; location / { # 这部份用来处理前端的资源 alias /data/www/domain.com/html/; try_files $uri $uri/ /index.html; } location /api/ { # 这部份/api/开头的请求代理到后端的接口上 proxy_pass http://x.x.x.x:4000; } location /admin/ { # 和上面一样 proxy_pass http://x.x.x.x:8000; } } "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241001/02f15696f7a460ba2ddfac0cd4ad20ff.png)