Rust Yew+Actix部署Nginx后无法调用后端API问题求助
解决方案
1. 配置Nginx反向代理后端API
当前Nginx仅托管前端静态文件,需要添加反向代理规则,让前端的API请求通过Nginx转发到Actix后端(localhost:8000)。修改后的完整Nginx配置如下:
server { listen 443 ssl; # IPv4 listen [::]:443 ssl; # IPv6 server_name my-portal.org; ssl_certificate /etc/letsencrypt/live/my-portal.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/my-portal.org/privkey.pem; ssl_dhparam /etc/letsencrypt/ssl-dhparams-2048.pem; #临时限制访问 auth_basic "Invitation Token"; auth_basic_user_file /etc/nginx/.htpasswd; # 反向代理后端API(根据实际接口前缀调整,这里假设所有API以/api开头) location /api/ { proxy_pass http://localhost:8000/api/; # 传递必要请求头,确保后端能正确识别请求来源 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; } # 如果后端有业务级WebSocket服务,添加以下配置(非Trunk开发用的ws) location /ws/ { proxy_pass http://localhost:8000/ws/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; 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; } location / { root /home/portal/my-portal/dist; try_files $uri $uri/ /index.html; } }
- 若后端接口没有统一前缀(比如直接是
/test),可将/api/对应的location块替换为针对具体接口的配置,例如:
location /test { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
2. 调整前端API请求地址
本地开发时前端可能直接请求localhost:8000,部署后需改为相对路径或当前域名的API路径,避免跨域和混合内容问题。在Yew项目的Rust代码中调整API地址:
// 使用相对路径,自动适配当前域名 const API_BASE: &str = "/api"; // 发起请求示例 let response = reqwest::get(format!("{}/test", API_BASE)).await?;
3. 解决_trunk/ws连接错误
_trunk/ws是Trunk开发服务器的热重载WebSocket连接,生产环境不应出现该请求,排查及修复步骤:
- 确认已执行
trunk build --release构建生产包,而非用trunk serve运行开发服务器。 - 清除浏览器缓存或使用无痕模式访问,避免加载旧的开发环境代码。
- 检查项目代码中是否存在硬编码的
_trunk/ws连接,移除相关开发调试代码。
4. 验证与测试
- 重启Nginx使配置生效:
sudo systemctl restart nginx - 确保Actix后端稳定运行在8000端口
- 打开浏览器开发者工具(F12)查看Network标签:
- 确认API请求地址为
https://my-portal.org/api/xxx,状态码正常(200系列) - 确认不再出现
_trunk/ws的连接请求
- 确认API请求地址为
额外注意事项
- 远程服务器防火墙无需对外开放8000端口,仅需允许本地Nginx转发请求即可。
- 使用反向代理后,前端请求与域名同源,原Actix的CORS配置可简化(仅保留允许
localhost:8000的规则即可,或直接移除)。
内容的提问来源于stack exchange,提问作者rek2
相关产品推荐
相关产品推荐

