1501 字
8 分钟
Nginx 进阶完全指南 2026:反向代理 + HTTPS + 负载均衡 + 限速 + 安全加固
Nginx 是目前最流行的 Web 服务器和反向代理,全球超过 30% 的网站使用它。它不只是静态文件服务器——正确配置的 Nginx 可以承担 HTTPS 终止、负载均衡、限速防护、WebSocket 代理等所有流量处理任务。
本文以生产环境实战为导向,完整覆盖 Nginx 进阶配置的各个方面。
一、安装与目录结构
apt update && apt install -y nginx
nginx -v# 主要目录# /etc/nginx/nginx.conf 主配置文件# /etc/nginx/conf.d/ 站点配置目录(推荐在这里建文件)# /var/log/nginx/access.log 访问日志# /var/log/nginx/error.log 错误日志# /var/www/html/ 默认 Web 根目录
nginx -t # 检查语法nginx -s reload # 热重载(不中断现有连接)二、配置文件层次结构
main # 全局配置├── events { } # 事件处理(worker连接数等)└── http { } # HTTP 相关 ├── upstream { } # 后端服务器组(负载均衡用) └── server { } # 虚拟主机 └── location { } # URL 匹配规则三、反向代理配置
3.1 基础反向代理
upstream myapp_backend { server 127.0.0.1:8000; keepalive 32; # 保持32个长连接,减少 TCP 握手开销}
server { listen 80; server_name example.com www.example.com;
location / { proxy_pass http://myapp_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; proxy_set_header X-Forwarded-Proto $scheme;
# 超时配置 proxy_connect_timeout 10s; proxy_send_timeout 60s; proxy_read_timeout 60s; }}3.2 WebSocket 代理
location /ws/ { proxy_pass http://myapp_backend; proxy_http_version 1.1; # 必须!WebSocket 不支持 HTTP/1.0 proxy_set_header Upgrade $http_upgrade; # 协议升级 proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_read_timeout 3600s; # 长连接不能60s超时}3.3 location 匹配优先级
# 精确匹配(最高优先级)location = /favicon.ico { return 204; }
# 正则匹配(区分大小写用 ~,不区分用 ~*)location ~* \.(jpg|png|css|js|woff2)$ { expires 30d; add_header Cache-Control "public, immutable";}
# 前缀匹配带 ^~(阻止后续正则检查)location ^~ /api/ { proxy_pass http://api_backend; }
# 普通前缀匹配location / { proxy_pass http://myapp_backend; }
# 优先级:= > ^~ > ~ > ~* > 普通前缀四、HTTPS 配置(Let’s Encrypt)
4.1 申请证书
apt install -y certbot python3-certbot-nginx
# --nginx 插件自动修改 Nginx 配置certbot --nginx -d example.com -d www.example.com
# 证书位置:# /etc/letsencrypt/live/example.com/fullchain.pem# /etc/letsencrypt/live/example.com/privkey.pem
certbot renew --dry-run # 测试自动续期certbot certificates # 查看已申请证书4.2 完整 HTTPS 配置模板
# HTTP 强制跳 HTTPSserver { listen 80; listen [::]:80; server_name example.com www.example.com; return 301 https://$host$request_uri;}
server { listen 443 ssl; listen [::]:443 ssl; http2 on; # 开启 HTTP/2(Nginx 1.25.1+) server_name example.com www.example.com;
# SSL 证书 ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 协议和加密套件(Mozilla Intermediate 推荐) ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers off;
# SSL 会话缓存(减少握手开销) ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d; ssl_session_tickets off;
# OCSP Stapling(加速证书验证) ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem; resolver 1.1.1.1 8.8.8.8 valid=300s;
# 安全响应头 add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always;
location /api/ { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; }
location / { root /var/www/myapp; try_files $uri $uri/ /index.html; # SPA 路由支持 }}五、负载均衡
# 轮询(默认)upstream backend_rr { server 10.0.0.1:8000; server 10.0.0.2:8000; server 10.0.0.3:8000; keepalive 64;}
# 加权轮询(服务器性能不同)upstream backend_weighted { server 10.0.0.1:8000 weight=3; server 10.0.0.2:8000 weight=1;}
# 最少连接(请求耗时差异大)upstream backend_lc { least_conn; server 10.0.0.1:8000; server 10.0.0.2:8000;}
# IP 哈希(session 粘性)upstream backend_iphash { ip_hash; server 10.0.0.1:8000; server 10.0.0.2:8000;}
# 含 backup 备用服务器upstream backend_ha { server 10.0.0.1:8000; server 10.0.0.2:8000; server 10.0.0.3:8000 backup; # 主服务器全部故障时启用}
server { location / { proxy_pass http://backend_rr; # 被动健康检查:后端报错自动切换到下一台 proxy_next_upstream error timeout http_500 http_502 http_503; }}六、限速与防护
# http 块中定义限速区域http { limit_req_zone $binary_remote_addr zone=general:10m rate=20r/s; limit_req_zone $binary_remote_addr zone=login:10m rate=1r/m; # 登录接口 limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_req_status 429; # 触发限速返回 429,而不是默认的 503 limit_conn_status 429;}
server { # 全局限速 limit_req zone=general burst=30 nodelay; limit_conn perip 50;
location /api/ { limit_req zone=api burst=50 nodelay; # burst=50:允许突发50个请求 limit_conn perip 20; proxy_pass http://backend; }
location /auth/login { limit_req zone=login burst=3 nodelay; # 登录接口严格限速 limit_conn perip 5; proxy_pass http://backend; }
# 请求体大小限制(文件上传) client_max_body_size 10m;
# 下载带宽限速 location /download/ { limit_rate 2m; # 每连接最大 2MB/s limit_rate_after 5m; # 前 5MB 不限速,之后再限 alias /var/www/files/; }}七、Gzip 压缩 + 代理缓存
http { # Gzip 压缩 gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; # 1-9,6是速度与压缩比的平衡点 gzip_min_length 1000; # 小于 1KB 不压缩 gzip_types text/plain text/css application/json application/javascript image/svg+xml font/truetype application/font-woff2;
# 代理缓存配置 proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m use_temp_path=off;}
server { # 静态资源永久缓存(强缓存) location /static/ { expires 1y; add_header Cache-Control "public, immutable"; }
# API 响应代理缓存 location /api/public/ { proxy_cache mycache; proxy_cache_valid 200 302 5m; proxy_cache_valid 404 1m; proxy_cache_use_stale error timeout updating; proxy_cache_lock on; add_header X-Cache-Status $upstream_cache_status; proxy_cache_methods GET HEAD; proxy_pass http://backend; }}八、生产 nginx.conf 完整模板
user nginx;worker_processes auto;worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log warn;pid /var/run/nginx.pid;
events { worker_connections 4096; use epoll; multi_accept on;}
http { include /etc/nginx/mime.types; default_type application/octet-stream;
sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65;
server_tokens off; # 隐藏 Nginx 版本号
log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" rt=$request_time ' 'uct=$upstream_connect_time urt=$upstream_response_time';
access_log /var/log/nginx/access.log main;
limit_req_zone $binary_remote_addr zone=general:10m rate=20r/s; limit_req_status 429;
gzip on; gzip_vary on; gzip_comp_level 6; gzip_min_length 1000; gzip_types text/plain text/css application/json application/javascript image/svg+xml;
include /etc/nginx/conf.d/*.conf;}九、常见问题排查
nginx -t && nginx -s reload # 检查语法并热重载tail -f /var/log/nginx/error.logtail -f /var/log/nginx/access.log | grep '" [45]' # 只看报错请求| 错误现象 | 可能原因 | 解决方向 |
|---|---|---|
502 Bad Gateway | 后端服务未运行 | 检查后端服务状态和 upstream 地址 |
504 Gateway Timeout | 后端响应过慢 | 增大 proxy_read_timeout |
413 Request Entity Too Large | 请求体超限 | 增大 client_max_body_size |
429 Too Many Requests | 触发限速 | 调整 limit_req rate 和 burst |
| 静态文件 403 | 权限错误 | chown -R nginx:nginx /var/www |
| HTTPS 证书错误 | 证书过期 / 路径错误 | certbot renew;检查证书路径 |
| WebSocket 断连 | 超时设置过短 | 设置 proxy_read_timeout 3600s |
相关文章:
- Linux 服务器初始化安全配置:买完 VPS 必做的 12 件事
- Docker 完全指南 2026:Compose 多服务编排与生产部署
- Let’s Encrypt + Certbot 完全指南:自动申请和续期 HTTPS 证书
- SSH 隧道完全指南:本地/远程/动态端口转发
- FastAPI 完全指南 2026:从零构建高性能异步 Python API
本文基于 Nginx 1.26.x(stable)验证。
http2 on指令在 Nginx 1.25.1+ 适用,旧版请用listen 443 ssl http2写法。
Nginx 进阶完全指南 2026:反向代理 + HTTPS + 负载均衡 + 限速 + 安全加固
https://971918.xyz/posts/docs/nginx-reverse-proxy-guide/