nginx的常规配置 user nginx; worker_processes auto; # 自动匹配 CPU 核心数 error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; # 优化连接处理 events { worker_connections 2048; multi_accept on; use epoll; } http { 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 $http_x_forwarded_for; access_log /var/log/nginx/access.log main; # 基础性能优化 sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; server_tokens off; # 代理缓存路径需要提前创建 /data/nginx/cache 并设置权限 proxy_cache_path /data/nginx/cache levels1:2 keys_zonemy_cache:10m max_size10g inactive60m use_temp_pathoff; proxy_cache_key $scheme$request_method$host$request_uri; # 后端服务器组最少连接算法 upstream backend { least_conn; # 后端服务器带权重和被动健康检查 server backend1.example.com weight3 max_fails3 fail_timeout30s; server backend2.example.com weight1 max_fails3 fail_timeout30s; server backend3.example.com weight1 max_fails3 fail_timeout30s; # 如果使用 Nginx Plus 或第三方健康检查模块可启用主动检查 # health_check interval5s fails3 passes2; } server { listen 80; server_name example.com; # 替换为你的域名 # HTTPS 配置需要时取消注释并配置证书 # listen 443 ssl http2; # ssl_certificate /etc/nginx/ssl/example.com.crt; # ssl_certificate_key /etc/nginx/ssl/example.com.key; access_log /var/log/nginx/example.access.log main; error_log /var/log/nginx/example.error.log; # 主代理 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; proxy_set_header X-Forwarded-Proto $scheme; # 启用缓存 proxy_cache my_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_methods GET HEAD; # 当后端异常时提供陈旧缓存生产建议开启 # proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; } # 本机健康检查端点可用于外部负载均衡或监控 location /nginx-health { access_log off; return 200 healthy\n; add_header Content-Type text/plain; } } }具体模板参考以上上前必须完成的调配配置项说明server_name改成你的实际域名如 api.yourdomain.com。upstream中的服务器地址将 backend1.example.com 等替换为后端真实 IP 或内网域名并按需调整 weight。被动健康检查参数max_fails3 fail_timeout30s 表示 30 秒内失败 3 次则摘除可根据业务调整。缓存目录确保 /data/nginx/cache 存在且 nginx 用户有读写权限否则 proxy_cache 会失效。日志目录确保 /var/log/nginx/ 存在并可写或改为你的日志路径。HTTPS如对外提供服务建议启用 SSL 并将 HTTP 强制跳转至 HTTPS。主动健康检查开源 Nginx 不支持 health_check;如需该功能可升级到 Nginx Plus 或编译 ngx_http_upstream_check_module 模块然后启用注释中的指令。配置文件保存后通过 nginx -t 检查语法确认无误后执行 nginx -s reload 热加载即可。这样既具备了高效的负载均衡能力又通过缓存和连接优化满足了生产环境的要求。