1. 核心概念
配置项 | 作用 | 示例值 |
---|---|---|
.env 文件 |
定义环境变量(如 API 基址) | VITE_APP_BASE_API='/pipe-api' |
Axios baseURL |
请求的公共路径前缀 | baseURL: import.meta.env.VITE_APP_BASE_API |
Nginx proxy_pass |
将请求转发到后端服务器 | proxy_pass http://127.0.0.1:8084/pipe-api/; |
2. 开发环境( npm run dev
)
- 流程 :
浏览器 → Vite 开发服务器 → 代理到后端 - 关键配置:
arduino
// vite.config.js
server: {
proxy: {
'/pipe-api': {
target: 'http://127.0.0.1:8084', // 后端地址
changeOrigin: true,
},
},
}
- 行为:
-
- 请求
/pipe-api/user
→ Vite 代理为http://127.0.0.1:8084/pipe-api/user
。 - 无需 Nginx,代理由 Vite 本地服务器完成。
- 请求
3. 生产环境( npm run build
+ Nginx)
- 流程 :
浏览器 → Nginx → 后端服务器 - 关键配置:
perl
location ^~/pipe-api/ {
proxy_pass http://127.0.0.1:8084/pipe-api/; # 保留路径前缀
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
- 行为:
-
- 请求
https://你的域名/pipe-api/user
→ Nginx 转发到http://127.0.0.1:8084/pipe-api/user
。 VITE_APP_BASE_API
的值/pipe-api
会被静态注入到打包后的代码中。
- 请求
4. 环境变量与路径规则
环境 | .env 文件 |
实际请求路径 | 代理目标 |
---|---|---|---|
开发 | VITE_APP_BASE_API='/pipe-api' |
http://localhost:5173/pipe-api/user |
http://127.0.0.1:8084/pipe-api/user |
生产 | VITE_APP_BASE_API='/pipe-api' |
https://域名/pipe-api/user |
http://127.0.0.1:8084/pipe-api/user |
5. 重要注意事项
VITE_
前缀:
-
- 只有以
VITE_
开头的变量会被注入到前端代码(import.meta.env
)。 - 非
VITE_
变量仅在vite.config.js
中可用(如process.env.SECRET_KEY
)。
- 只有以
- Nginx 斜杠规则:
-
proxy_pass http://127.0.0.1:8084/pipe-api/;
→ 保留/pipe-api
前缀(后端需兼容)。proxy_pass http://127.0.0.1:8084/;
→ 删除/pipe-api
前缀(后端直接接收/user
)。
- 生产环境安全:
-
- 不要在前端暴露真实 IP 或端口(如
http://1.2.3.4:8084
),始终用 Nginx 代理隐藏。
- 不要在前端暴露真实 IP 或端口(如
6. 常见问题排查
问题现象 | 可能原因 | 解决方案 |
---|---|---|
生产环境 404 | Nginx proxy_pass 路径不匹配 |
检查后端是否需要 /pipe-api 前缀。 |
开发环境跨域 | Vite 代理未生效 | 确认 vite.config.js 代理配置正确。 |
变量未替换 | 变量名未以 VITE_ 开头 |
修改变量名为 VITE_APP_XXX 。 |
7. 一键配置总结
ini
# .env.development
VITE_APP_BASE_API = '/pipe-api'
# .env.production
VITE_APP_BASE_API = '/pipe-api'
php
// Axios 配置(通用)
const service = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_API,
timeout: 60000,
});
bash
# Nginx 生产配置
location ^~/pipe-api/ {
proxy_pass http://backend-server:8084/pipe-api/;
proxy_set_header Host $host;
}
8. 流程图解
bash
开发环境:
浏览器 → `/pipe-api/user` → Vite 代理 → `http://127.0.0.1:8084/pipe-api/user`
生产环境:
浏览器 → `https://域名/pipe-api/user` → Nginx → `http://127.0.0.1:8084/pipe-api/user`
理解口诀:
- 开发靠 Vite,生产靠 Nginx
- 路径前缀一致,变量注入要带 `VITE_
- 斜杠定生死,代理规则要对齐