文章目錄
- 前言
- 解決方案:使用 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 | 檢查配置文件語法是否正確 |