Nginx 核心配置实战指南

Nginx 核心配置实战指南 1. Nginx 核心配置入门指南第一次接触 Nginx 配置时我盯着那些大括号嵌套的代码块看了整整半小时。直到后来才发现Nginx 的配置文件就像乐高积木由几个关键模块拼装而成。最让我惊喜的是只需要修改几十行配置就能让服务器性能提升数倍。全局配置是每个 Nginx 管理员必须掌握的基础。还记得我刚开始工作时有台服务器总是莫名其妙崩溃。后来发现是 worker_processes 设成了1而服务器有16核CPU。改成 auto 后性能立刻提升了8倍。这里分享几个关键参数user nginx; # 用专门的nginx用户运行更安全 worker_processes auto; # 自动匹配CPU核心数 error_log /var/log/nginx/error.log warn; # 错误日志设为警告级别 pid /run/nginx.pid; # 进程ID文件位置事件模块的配置直接影响并发处理能力。曾经有个电商项目在促销时频繁报错调整以下参数后问题迎刃而解events { worker_connections 2048; # 每个worker能处理的连接数 multi_accept on; # 一次性接受所有新连接 use epoll; # Linux系统必选的高效模型 }2. HTTP 服务器核心配置实战http 模块是 Nginx 最复杂的部分也是功能最强大的区域。我处理过最棘手的案例是一个图片站点加载缓慢通过优化以下配置加载时间从3秒降到0.5秒http { include mime.types; # 文件类型映射 default_type application/octet-stream; # 默认MIME类型 # 日志格式定制 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; # 优化数据包发送效率 keepalive_timeout 65; # 保持连接超时时间 # 静态文件缓存设置 open_file_cache max1000 inactive20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; }Server 块配置是虚拟主机的核心。有次客户要求同一个IP服务多个域名我是这样配置的server { listen 80; server_name example.com www.example.com; location / { root /var/www/html; index index.html; } # 错误页面定制 error_page 404 /404.html; location /404.html { internal; root /usr/share/nginx/html; } }3. 反向代理高级配置技巧反向代理是 Nginx 最常用的功能之一。记得有个Java应用经常超时通过以下配置解决了问题location /api/ { proxy_pass http://backend_server; 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_connect_timeout 75s; proxy_read_timeout 300s; proxy_send_timeout 300s; # 缓冲设置 proxy_buffering on; proxy_buffer_size 16k; proxy_buffers 4 32k; }WebSocket 代理配置曾让我踩过坑。有个实时监控系统需要长连接正确的配置应该是location /realtime/ { proxy_pass http://websocket_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_read_timeout 3600s; # 长连接超时时间 }4. 负载均衡实战策略负载均衡配置直接影响服务可用性。去年双十一我们通过以下配置扛住了流量洪峰upstream backend { server 192.168.1.101:8080 weight5; # 权重配置 server 192.168.1.102:8080; server 192.168.1.103:8080 backup; # 备用服务器 # 健康检查 check interval3000 rise2 fall5 timeout1000; } server { location / { proxy_pass http://backend; # 其他代理配置... } }会话保持在某些场景下很关键。电商购物车需要IP哈希策略upstream shopping { ip_hash; # 基于客户端IP的会话保持 server 192.168.2.101:8080; server 192.168.2.102:8080; }5. 动静分离优化方案动静分离能显著提升性能。有个门户网站通过以下配置吞吐量提升了3倍server { # 静态资源处理 location ~* \.(jpg|jpeg|png|gif|css|js|ico)$ { root /var/www/static; expires 30d; # 客户端缓存30天 access_log off; # 关闭日志减少IO } # 动态请求转发 location / { proxy_pass http://dynamic_backend; } }单页应用需要特殊处理。Vue/React项目这样配置location / { root /var/www/spa; try_files $uri $uri/ /index.html; }6. 安全加固与性能调优安全配置不容忽视。去年某次安全扫描后我们增加了这些配置# 隐藏Nginx版本信息 server_tokens off; # 安全头部 add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection 1; modeblock; # 限制HTTP方法 if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; }Gzip 压缩能有效减少传输量。内容型网站建议这样配置gzip on; gzip_min_length 1k; gzip_comp_level 6; gzip_types text/plain text/css application/json application/javascript text/xml; gzip_vary on;7. HTTPS 最佳实践HTTPS 已成为标配。这是我为金融项目做的配置server { listen 443 ssl http2; server_name secure.example.com; ssl_certificate /etc/ssl/certs/example.com.crt; ssl_certificate_key /etc/ssl/private/example.com.key; # 安全协议配置 ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; # HSTS 安全增强 add_header Strict-Transport-Security max-age63072000; includeSubdomains; preload; }HTTP 跳转 HTTPS是必须的server { listen 80; server_name example.com; return 301 https://$host$request_uri; }8. 高级日志与监控配置精细化日志对排查问题至关重要。这是我们使用的日志格式log_format detailed $remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $request_time $upstream_response_time; access_log /var/log/nginx/access.log detailed;状态监控页面可以帮助运维location /nginx_status { stub_status on; access_log off; allow 192.168.1.0/24; deny all; }9. 常见问题排查技巧遇到502错误时我通常会检查这些后端服务是否正常运行proxy_pass地址是否正确防火墙是否放行端口连接超时设置是否合理性能瓶颈排查步骤# 查看连接状态 netstat -n | awk /^tcp/ {S[$NF]} END {for(a in S) print a, S[a]} # 监控错误日志 tail -f /var/log/nginx/error.log # 压力测试工具 ab -n 1000 -c 100 http://test.example.com/10. 配置管理建议经过多年实践我总结出这些经验使用include分割大配置文件为每个虚拟主机创建单独文件版本控制所有配置变更变更前备份原配置多环境配置管理示例# conf.d/main.conf include /etc/nginx/conf.d/*.conf; # conf.d/site1.conf server { listen 80; server_name site1.example.com; # 其他配置... }