Nginx 配置实战(2026最新版):反向代理+负载均衡+HTTPS+性能优化一网打尽 Nginx 是后端开发必备技能。本文从零开始讲透 Nginx 配置涵盖反向代理、负载均衡、HTTPS、静态资源缓存、Gzip 压缩等核心场景每个配置都有完整示例收藏备用一、Nginx 核心概念1.1 Nginx 是什么Nginx发音Engine X是高性能的 HTTP 服务器和反向代理服务器角色说明静态文件服务器直接处理 HTML/CSS/JS/图片速度极快反向代理将请求转发到后端服务Node.js/Java/Python负载均衡多台服务器分摊流量SSL/TLS 终止统一处理 HTTPS后端无需关心证书限流/防刷控制请求速率防止 DDoSNginx 核心架构1 个 Master 进程管理N 个 Worker 进程处理请求N CPU核数事件驱动 非阻塞 IO单机轻松支撑 10 万并发二、安装与基础配置2.1 安装 Nginx# CentOS / 宝塔已有可跳过 sudo yum install -y nginx # Ubuntu / Debian sudo apt update sudo apt install -y nginx # 启动并设置开机启动 sudo systemctl start nginx sudo systemctl enable nginx # 验证安装 nginx -v # nginx/1.24.02.2 配置文件结构/etc/nginx/ ├── nginx.conf # 主配置文件 ├── conf.d/ # 自定义配置目录推荐在这里写 │ ├── default.conf │ ├── mysite.conf │ └── api.conf └── sites-enabled/ # Ubuntu 风格软链接2.3 nginx.conf 全局配置解析# /etc/nginx/nginx.conf # 工作进程数设为 auto自动匹配 CPU 核数 worker_processes auto; # 错误日志 error_log /var/log/nginx/error.log warn; # PID 文件 pid /var/run/nginx.pid; events { # 每个 worker 进程最大连接数 worker_connections 1024; # 使用 epollLinux 高效 IO 模型 use epoll; # 允许一次性接受多个连接 multi_accept on; } http { # 包含 MIME 类型定义 include /etc/nginx/mime.types; default_type application/octet-stream; # 日志格式 log_format main $remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent; access_log /var/log/nginx/access.log main; # 高效文件传输零拷贝 sendfile on; tcp_nopush on; tcp_nodelay on; # 连接保活时间 keepalive_timeout 65; # 隐藏版本号安全 server_tokens off; # 包含所有站点配置 include /etc/nginx/conf.d/*.conf; }三、核心场景配置3.1 静态网站部署Vue3/React 前端# /etc/nginx/conf.d/frontend.conf server { listen 80; server_name yourdomain.com www.yourdomain.com; # 前端打包文件目录 root /var/www/dist; index index.html; # Vue Router / React Router History 模式支持 # 关键所有路径都返回 index.html让前端路由处理 location / { try_files $uri $uri/ /index.html; } # 静态资源长期缓存 # 带 hash 的文件如 app.a1b2c3.js永久缓存 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ { expires max; add_header Cache-Control public, immutable; access_log off; # 不记录静态资源访问日志减少 IO } # HTML 文件不缓存确保前端更新能及时生效 location ~* \.html$ { expires -1; add_header Cache-Control no-cache, no-store, must-revalidate; } # Gzip 压缩 gzip on; gzip_min_length 1k; gzip_comp_level 6; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xmlrss text/javascript image/svgxml; gzip_vary on; gzip_proxied any; }3.2 反向代理Node.js / Java 后端# /etc/nginx/conf.d/api.conf server { listen 80; server_name api.yourdomain.com; # 反向代理到 Node.js端口3000 location /api/ { # 转发到后端 proxy_pass http://127.0.0.1:3000; # 必须设置的 Header 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; # 缓冲区设置提高性能 proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 16k; } # WebSocket 支持 location /ws/ { proxy_pass http://127.0.0.1:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_read_timeout 3600s; # WebSocket 长连接超时设大 } # 文件上传代理 location /upload/ { proxy_pass http://127.0.0.1:3000; client_max_body_size 100m; # 允许最大 100MB 文件 proxy_request_buffering off; # 大文件不缓冲直接流式转发 } }3.3 负载均衡# /etc/nginx/conf.d/loadbalance.conf # 定义上游服务器组 upstream backend_servers { # 负载均衡策略 # 默认轮询Round Robin # ip_hash同一IP总访问同一服务器粘性会话 # least_conn最少连接数 ip_hash; # 会话保持适合有状态服务 server 192.168.1.10:8080 weight3; # weight权重流量占比更大 server 192.168.1.11:8080 weight2; server 192.168.1.12:8080 weight1; # 备用服务器只有其他服务器都挂了才用 server 192.168.1.13:8080 backup; # 健康检查需要 Nginx Plus 或 nginx_upstream_check_module # 这里用 max_fails 和 fail_timeout 做基础故障转移 server 192.168.1.10:8080 max_fails3 fail_timeout30s; } server { listen 80; server_name app.yourdomain.com; 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_next_upstream error timeout http_500 http_502 http_503; } }四、HTTPS 配置4.1 Lets Encrypt 免费 SSL 证书# 安装 Certbot sudo apt install -y certbot python3-certbot-nginx # 申请证书自动修改 Nginx 配置 sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com # 自动续期已自动创建 cron 任务验证方式 sudo certbot renew --dry-run4.2 HTTPS 完整配置# /etc/nginx/conf.d/https.conf server { listen 80; server_name yourdomain.com www.yourdomain.com; # HTTP 强制跳转 HTTPS return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name yourdomain.com www.yourdomain.com; # SSL 证书 ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem; # SSL 安全配置 ssl_protocols TLSv1.2 TLSv1.3; # 禁用旧版本TLSv1.0/1.1 ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384; 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; resolver 8.8.8.8 8.8.4.4 valid300s; # HSTS告诉浏览器永远用 HTTPS add_header Strict-Transport-Security max-age63072000 always; # 安全 Header add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection 1; modeblock; root /var/www/dist; index index.html; location / { try_files $uri $uri/ /index.html; } }五、性能优化配置5.1 Gzip Brotli 压缩http { # Gzip通用支持 gzip on; gzip_min_length 1k; gzip_comp_level 5; # 1-9越高压缩率越高但 CPU 消耗越多5 是平衡点 gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml image/svgxml; gzip_vary on; gzip_disable MSIE [1-6]\.; # 预压缩文件Vite/Webpack 构建时生成 .gz 文件Nginx 直接返回 gzip_static on; }5.2 限流配置http { # 定义限流区IP 维度每秒 10 个请求 limit_req_zone $binary_remote_addr zoneapi_limit:10m rate10r/s; # 定义连接数限制 limit_conn_zone $binary_remote_addr zoneconn_limit:10m; server { location /api/ { # 应用限流burst20 允许短暂突发nodelay 不排队直接拒绝 limit_req zoneapi_limit burst20 nodelay; # 每IP最多50个并发连接 limit_conn conn_limit 50; # 限流时返回 429 limit_req_status 429; proxy_pass http://127.0.0.1:3000; } } }六、常见问题解决❌ 问题1Vue3 刷新页面 404# 原因Nginx 找不到路由对应的文件 # 解决加 try_files所有请求都返回 index.html location / { try_files $uri $uri/ /index.html; # ✅ $uri先找对应文件 # ✅ $uri/再找目录 # ✅ /index.html都找不到就返回首页 }❌ 问题2跨域CORS问题location /api/ { proxy_pass http://127.0.0.1:3000; # 方法1在 Nginx 层处理 CORS不推荐在后端处理更好 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,Authorization,Content-Type; add_header Access-Control-Max-Age 1728000; return 204; } # 方法2推荐代理到后端让后端处理 CORS # proxy_pass 后后端会返回正确的 CORS 头 }❌ 问题3上传大文件 413 错误server { # 默认只允许 1MB增大限制 client_max_body_size 200m; # 上传超时大文件传输需要更长时间 client_body_timeout 300s; proxy_send_timeout 300s; proxy_read_timeout 300s; }七、常用命令速查# 测试配置文件语法 nginx -t # 重新加载配置不中断服务 nginx -s reload # 优雅停止处理完当前请求后停止 nginx -s quit # 立即停止 nginx -s stop # 查看 Nginx 进程 ps aux | grep nginx # 查看访问日志实时 tail -f /var/log/nginx/access.log # 查看错误日志 tail -f /var/log/nginx/error.log # 查看 Nginx 状态需要 stub_status 模块 curl http://127.0.0.1/nginx_status八、总结Nginx 配置掌握这几个核心场景就够用了场景关键配置前端部署try_files $uri /index.html反向代理proxy_passproxy_set_header负载均衡upstreamip_hash/least_connHTTPSssl_certificateTLSv1.2/1.3限流limit_req_zonelimit_req性能gzipexpiressendfile运维配置踩过哪些坑欢迎评论区分享点赞收藏持续更新 Linux/运维实战干货标签Nginx | Linux | 运维 | 反向代理 | HTTPS