Nginx作为高性能的HTTP和反向代理服务器,在实战中经常用于代理服务,以实现负载均衡、高可用性、安全性增强、缓存优化等目的。以下是一些常见的Nginx代理服务实战场景:
1. 基本反向代理配置
将外部请求转发到内部服务器,比如将HTTP请求代理到运行在8080端口的后端服务器:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
2. 负载均衡配置
将请求均匀地分布到多个后端服务器:
upstream backend {
server backend1.example.com weight=1;
server backend2.example.com:8080;
server backend3.example.com:8080 backup; # 作为备选服务器
}
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://backend;
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. 健康检查
确保Nginx只将请求转发给健康的后端服务器:
upstream backend {
server backend1.example.com:8080;
server backend2.example.com:8080;
# 使用第三方模块 ngx_http_upstream_check_module 实现健康检查
check interval=30s rise=2 fall=5 timeout=10s;
}
server {
# ...
}
4. WebSocket代理
Nginx可以作为WebSocket代理,转发WebSocket请求:
server {
listen 80;
server_name yourdomain.com;
location /ws {
proxy_pass http://websocket-backend:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
5. SSL终止与HTTPS代理
Nginx作为SSL终端节点,处理客户端加密请求,并将解密后的请求转发至后端服务器:
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /path/to/your/server.crt;
ssl_certificate_key /path/to/your/server.key;
location / {
proxy_pass http://backend-servers;
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 https;
}
}
6. 缓存优化
Nginx可以对后端服务器的响应进行缓存,减少后端压力:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
# ...
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_key $scheme$proxy_host$request_uri;
proxy_cache_valid 200 1h;
}
}
以上仅为基本示例,实际配置时需根据业务需求调整,并充分考虑安全性、性能和可维护性。