Nginx 反向代理配置详解
Nginx 是高性能的 HTTP 和反向代理服务器。本文详解配置方法。
一、基础配置
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend: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;
}
}
二、负载均衡
轮询(默认)
upstream backend {
server 192.168.1.1:8080;
server 192.168.1.2:8080;
}
权重
upstream backend {
server 192.168.1.1:8080 weight=3;
server 192.168.1.2:8080 weight=1;
}
ip_hash
upstream backend {
ip_hash;
server 192.168.1.1:8080;
server 192.168.1.2:8080;
}
三、性能优化
开启缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m;
location / {
proxy_cache my_cache;
proxy_cache_valid 200 10m;
}
开启压缩
gzip on;
gzip_types text/plain application/json;
gzip_min_length 1k;
四、常见问题
- 502 Bad Gateway:后端服务不可用
- 504 Gateway Timeout:后端响应超时
- 413 Request Entity Too Large:请求体过大