文章目录
- 前言
- 解决方案:使用 Nginx 做统一反向代理
前言
在多人开发任务中,如果不同人负责不同的后端接口服务开发,那么就面临着每个人的服务部署到不同的端口上,甚至有的人的服务部署在不同的服务器上。这时候前端如果想要调用后端的接口,就非常麻烦。
比如下面这种情况:
-
开发者 A 的接口部署在 http://localhost:5051/api/…
-
开发者 B 的接口部署在 http://localhost:5351/api/…
-
开发者 C 的服务部署在另一台服务器上:http://remote-server.com:8000/items/…
前端要分别调用这些接口,就需要处理多个端口、多个 IP 地址,还要配置跨域等问题,既复杂又容易出错。
解决方案:使用 Nginx 做统一反向代理
我们可以通过部署一个 Nginx 服务来统一入口端口,例如统一通过 http://api.example.com:5053 访问不同的后端接口,内部再根据请求路径转发给对应的服务。这样,前端只需要记住一个地址和端口,调用 /api1/、/api2/、/api3/ 即可访问不同的服务。
服务器端nginx安装命令:
# 在 Ubuntu上安装
sudo apt update
sudo apt install nginx -y# 在 CentOS上安装
sudo yum install epel-release -y
sudo yum install nginx -y
Nginx 配置示例:
在服务器上安装 Nginx 后,编辑配置文件(如 /etc/nginx/conf.d/api_gateway.conf),示例如下:
编辑命令:sudo vi /etc/nginx/nginx.conf
server {listen 5053;server_name api.example.com;# 代理开发者 A 的服务:本机 5051 端口location /api1/ {proxy_pass http://127.0.0.1:5051/api/;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}# 代理开发者 B 的服务:本机 5351 端口location /api2/ {proxy_pass http://127.0.0.1:5351/api/;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}# 代理开发者 C 的服务:远程服务器location /api3/ {proxy_pass http://remote-server.com:8000/items/;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}
}
请求映射关系
前端请求路径 | 实际代理后的路径 |
---|---|
http://api.example.com:5053/api1/xxx | → http://127.0.0.1:5051/api/xxx |
http://api.example.com:5053/api2/xxx | → http://127.0.0.1:5351/api/xxx |
http://api.example.com:5053/api3/xxx | → http://remote-server.com:8000/items/xxx |
这样做的好处是:
- 安全性更高(隐藏内部服务细节)
- 跨域问题由后端集中处理(CORS配置)
- 负载均衡和路由管理更灵活
- 前端无需处理多端口逻辑
Nginx常用命令:
操作 | 命令 | 说明 |
---|---|---|
启动 Nginx | sudo systemctl start nginx | 启动服务 |
停止 Nginx | sudo systemctl stop nginx | 停止服务 |
重启 Nginx | sudo systemctl restart nginx | 重启服务(配置变更后常用) |
重新加载配置 | sudo nginx -s reload | 热重载配置文件(不中断服务) |
查看状态 | sudo systemctl status nginx | 查看服务是否运行中 |
查看版本 | nginx -v | 查看安装版本 |
测试配置 | sudo nginx -t | 检查配置文件语法是否正确 |