Nginx 反向代理配置指南
一、Nginx 安装与基础
安装
# Ubuntu / Debian
sudo apt-get install -y nginx
# CentOS / RHEL
sudo yum install -y nginx
# Docker
docker run -d --name nginx -p 80:80 -p 443:443 --restart unless-stopped \
-v /etc/nginx/conf.d:/etc/nginx/conf.d:ro \
nginx:1.25-alpine
常用管理命令
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # 平滑重载配置(不中断服务)
sudo nginx -t # 测试配置语法
sudo nginx -T # 查看生效的全部配置
二、配置文件结构
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 自定义配置(推荐)
│ ├── app1.conf
│ └── app2.conf
├── sites-available/ # 站点配置(Debian 系)
│ └── default
├── sites-enabled/ # 已启用的站点(软链接)
│ └── default -> ../sites-available/default
└── snippets/ # 可复用的配置片段
三、反向代理基础配置
最简反向代理
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:5000;
}
}
完整反向代理配置(推荐)
server {
listen 80;
server_name example.com;
# 代理头部设置
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
# WebSocket 支持
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 传递客户端信息
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 $scheme;
# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓冲设置
proxy_buffering on;
proxy_buffer_size 16k;
proxy_buffers 8 32k;
}
}
四、负载均衡
基本负载均衡
upstream backend {
server 192.168.1.101:5000 weight=3;
server 192.168.1.102:5000 weight=2;
server 192.168.1.103:5000 weight=1;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
负载均衡策略
| 策略 | 配置 | 说明 |
|---|---|---|
| 轮询(默认) | 无需额外配置 | 按顺序逐一分配 |
| 加权轮询 | weight=N | 按权重分配 |
| IP Hash | ip_hash; | 同一 IP 固定访问同一后端 |
| 最少连接 | least_conn; | 分配给连接数最少的服务器 |
健康检查
upstream backend {
server 192.168.1.101:5000 max_fails=3 fail_timeout=30s;
server 192.168.1.102:5000 max_fails=3 fail_timeout=30s;
# 备用服务器
server 192.168.1.104:5000 backup;
}
五、HTTPS 配置
使用 Let's Encrypt 免费证书
sudo apt-get install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
手动配置 SSL
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL 优化
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# HSTS
add_header Strict-Transport-Security "max-age=31536000" always;
location / {
proxy_pass http://localhost:5000;
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 $scheme;
}
}
# HTTP 跳转 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
六、静态文件服务
server {
listen 80;
server_name static.example.com;
root /var/www/static;
index index.html;
location / {
try_files $uri $uri/ =404;
}
# 图片缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
七、实用配置片段
请求限流
# 定义限流区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://localhost:5000;
}
}
IP 访问控制
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
proxy_pass http://localhost:5000;
}
跨域配置
location /api/ {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
add_header Access-Control-Max-Age 86400;
return 204;
}
add_header Access-Control-Allow-Origin '*' always;
proxy_pass http://localhost:5000;
}
Gzip 压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
八、常见问题排查
# 查看错误日志
sudo tail -f /var/log/nginx/error.log
# 查看访问日志
sudo tail -f /var/log/nginx/access.log
# 常见错误
# 413 Request Entity Too Large → client_max_body_size 50M;
# 502 Bad Gateway → 后端服务未启动或端口错误
# 504 Gateway Timeout → proxy_read_timeout 设置过短或后端响应超时
在 http 块中添加:
client_max_body_size 50M;
最佳实践:将配置文件拆分到
conf.d/目录,每个应用一个独立.conf文件,修改后用nginx -t测试,再systemctl reload nginx平滑生效,避免中断服务。