Vue 生产环境跨域 Nginx 配置
2024-01-25 by dongnan
环境描述
前后端分离项目,分别是 Vue3前端框架 与 Gin后端框架。 
前端
- node版本 v20.10.0
- 构建工具 vite v5.0.10
- 框架版本 vue@3.3.12
- 访问地址 http://192.168.1x0.250/
- 监听端口 Nginx:80
后端
- go版本 go1.21.3
- 框架版本 gin v1.9.1
- API地址 http://localhost:8000/weixing
- 监听端口 Gin:8000
问题描述
将 vue 项目 打包(npm run build) dist/目录直接放在 nginx 服务器中,会遇到两个问题。
- 使用 vue-router路由时会返回404问题。
- 开发环境下的跨域配置无效,跨域问题重现了。
关于什么是跨域?请参考这里

解决方法
对于第1个路由404问题
项目vue-router 模式为 WebHistory ,所以 nginx 需要做如下配置:
location / {
        try_files $uri $uri/ /index.html;
}
对于第2个跨域问题
是开发环境与生产环境中请求URL地址发生变化,所以需要在 nginx 配置代理:
// 后端 localhost:8000
location /weixing {
        proxy_pass  http://localhost:8000/weixing;
}
完整的 Nginx 配置:
server {
    // other settings
    location / {
        try_files $uri $uri/ /index.html;
    }
    location /weixing {
        proxy_pass  http://localhost:8000/weixing;
    }
    // other settings
}
验证
再次请求API成功
