在vite.config.js中配置的server.proxy仅在Vite 开发服务器(即你运行npm run dev或yarn dev时)生效。当你将 Vue 3 项目打包(npm run build)并部署到 Nginx 后,这个配置文件不会被带进生产环境,Nginx 也完全不会读取vite.config.js文件。
1. 为什么无效?
- Vite 的代理原理:它基于 Node.js 的
http-proxy库,在开发时启动了一个中间件服务。浏览器访问http://localhost:3000/api,Vite 服务器接收请求后转发给http://localhost:8060。 - Nginx 的托管原理:Nginx 直接托管
dist目录下的静态文件(HTML/JS/CSS)。当浏览器请求/api时,请求直接打到 Nginx 监听的端口(如 80/443),Nginx 不会因为 Vite 的配置文件而自动代理。
2. 如何在 Nginx 中实现相同的代理效果?
你需要在Nginx 的配置文件(通常是nginx.conf或/etc/nginx/conf.d/your-project.conf)中手动添加反向代理配置。
假设你的 Vue 应用部署在/usr/share/nginx/html,后端接口在http://localhost:8060,配置如下:
server { listen 80; server_name your-domain.com; # 你的域名或 IP # 托管 Vue 静态文件 location / { root /usr/share/nginx/html; try_files $uri $uri/ /index.html; # 解决 Vue Router 刷新 404 问题 } # 代理 /api 请求(等效于 Vite 的 proxy 配置) location /api { proxy_pass http://localhost:8060; # 对应 target # 等效于 changeOrigin: true proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # 可选:如果你在 Vite 中配置了 rewrite,在这里对应修改 # 例如 Vite 的 rewrite: (path) => path.replace(/^\/api/, '') # 则这里 proxy_pass 末尾加斜杠:proxy_pass http://localhost:8060/; } }配置完成后,执行nginx -t检查语法,然后nginx -s reload重载配置即可生效。
3. 特别提醒:跨域(CORS)
- 在Vite 开发环境中,代理绕过了浏览器的跨域限制。
- 在Nginx 生产环境中,使用上述
proxy_pass同样绕过了跨域(因为请求是 Nginx 服务端转发的),不需要在后端代码中额外开启 CORS,除非前端直接请求后端 IP 而非通过 Nginx。
4. 补充:vite preview呢?
如果你运行npm run preview(即vite preview --port 3000),这个命令会启动一个生产预览服务器,此时server.proxy是生效的。但这仅用于本地预览,不适用于生产环境部署,且性能远不如 Nginx,不建议用这种方式替代 Nginx 对外提供服务。
总结:生产环境务必把代理逻辑写在 Nginx 配置中,vite.config.js里的server配置只属于开发环境。如果你对 Nginx 配置不熟悉,可以直接复制上面的location /api代码块使用。如果有路径重写等特殊需求,可以告诉我,我帮你调整配置。