Nginx单端口代理多个前后端服务的完整配置指南
Nginx单端口代理多个前后端服务的完整配置指南
一、核心配置原理
Nginx通过server
块监听指定端口,利用location
模块实现路径级别的请求分发。通过proxy_pass
指令将不同路径的请求转发至对应后端服务,同时可配置静态资源缓存策略。
二、完整配置示例
# 主配置文件 /etc/nginx/nginx.conf
worker_processes auto;
events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;# 上游服务定义upstream backend_api {server 127.0.0.1:8080; # 后端API服务server 127.0.0.1:8081 backup; # 备用节点}upstream web_server {server 127.0.0.1:3000; # 前端服务}server {listen 80;server_name localhost;# 静态资源缓存配置location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {expires 7d;root /usr/share/nginx/html/static;access_log off;}# 动态API接口代理location /api/ {proxy_pass http://backend_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_connect_timeout 60s;proxy_read_timeout 300s;}# 前端应用代理location / {proxy_pass http://web_server;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_cache_bypass $http_upgrade;}# 错误页面处理error_page 500 502 503 504 /50x.html;location = /50x.html {root /usr/share/nginx/html;}}
}
三、关键配置详解
1. 静态资源优化
- 路径匹配:使用正则表达式匹配文件类型
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {expires 7d; # 7天缓存root /usr/share/nginx/html/static; }
- 缓存策略:通过
expires
指令设置浏览器缓存时间
2. 动态接口代理
- 负载均衡配置:
upstream backend_api {server 127.0.0.1:8080 weight=3; # 主节点server 127.0.0.1:8081; # 从节点least_conn; # 最少连接策略 }
- 请求头传递:
proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
3. WebSocket支持
location /ws/ {proxy_pass http://websocket_server;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "Upgrade";
}
四、验证与调试
1. 配置检查
nginx -t
2. 访问测试
# 测试静态资源
curl http://localhost/css/style.css# 测试API接口
curl http://localhost/api/users# 测试前端应用
curl http://localhost/
3. 日志分析
- 访问日志:
/var/log/nginx/access.log
- 错误日志:
/var/log/nginx/error.log
五、高级配置技巧
1. HTTPS统一端口
server {listen 443 ssl;ssl_certificate /etc/nginx/ssl/fullchain.pem;ssl_certificate_key /etc/nginx/ssl/privkey.pem;location / {proxy_pass http://web_server;}
}
2. 路径重写
location /old-api/ {rewrite ^/old-api/(.*)$ /api/$1 break;proxy_pass http://backend_api;
}
3. 限流配置
location /api/ {limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;limit_req zone=api_limit burst=50;proxy_pass http://backend_api;
}
六、常见问题解决
1. 502 Bad Gateway
- 检查后端服务是否运行
- 增加超时时间:
proxy_connect_timeout 60s; proxy_read_timeout 300s;
2. 静态资源404
- 确认
root
路径是否存在 - 检查文件权限:
chmod -R 755 /usr/share/nginx/html/static
3. 跨域问题
location /api/ {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';if ($request_method = 'OPTIONS') {return 204;}proxy_pass http://backend_api;
}
通过以上配置,可实现Nginx在单个端口(如80/443)上同时代理多个前后端服务,满足生产环境的高性能需求。实际部署时需根据具体业务调整上游服务地址和缓存策略。