Nginx 性能优化与安全配置
🎯 学习目标
- 掌握 Nginx 性能优化的核心参数
- 学习生产环境的安全配置策略
- 了解高并发场景的优化技巧
- 实战:配置生产级 Nginx 服务器
⚡ 性能优化配置
1️⃣ 工作进程优化
1 2 3 4 5 6 7 8 9 10 11 12
| worker_processes auto;
worker_cpu_affinity auto;
events { worker_connections 4096; use epoll; multi_accept on; }
|
2️⃣ 文件描述符限制
1 2 3 4 5 6
| * soft nofile 65535 * hard nofile 65535
fs.file-max = 2097152
|
3️⃣ 核心性能参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 30;
client_body_buffer_size 128k; client_max_body_size 10m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; output_buffers 1 32k; postpone_output 1460;
keepalive_requests 100; reset_timedout_connection on;
open_file_cache max=200000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; }
|
4️⃣ Gzip 压缩配置
1 2 3 4 5 6 7 8 9 10 11 12
| gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml;
gzip_disable "msie6";
|
🔒 安全配置
1️⃣ 隐藏版本信息
1 2 3 4 5
| http { server_tokens off; more_set_headers 'Server: MyWebServer'; }
|
2️⃣ 限制请求大小
1 2 3 4 5 6 7 8 9 10 11 12
| client_max_body_size 10m; client_header_buffer_size 1k; large_client_header_buffers 4 4k;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; limit_req zone=one burst=20 nodelay;
limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 10;
|
3️⃣ SSL/TLS 安全配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| server { listen 443 ssl http2; server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256: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;
ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /etc/nginx/ssl/ca-bundle.crt;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "no-referrer-when-downgrade" always; add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always; }
|
4️⃣ 访问控制和IP限制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| location /admin { allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; }
if ($http_user_agent ~* (wget|curl|scanner) ) { return 403; }
valid_referers none blocked example.com *.example.com; if ($invalid_referer) { return 403; }
|
5️⃣ 防止常见攻击
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| if ($args ~* "union.*select.*\(" ) { return 403; }
if ($args ~* "php://input" ) { return 403; }
if ($args ~* "<script>" ) { return 403; }
location ~ /\.(htaccess|htpasswd|git|svn) { deny all; }
|
📊 缓存配置优化
静态资源缓存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ { expires 365d; add_header Cache-Control "public, immutable"; access_log off; }
location ~* \.html$ { expires 1h; add_header Cache-Control "public, must-revalidate"; }
location /api { expires -1; add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0"; }
|
Proxy Cache 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
server { location / { proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
location /api { proxy_cache_bypass $http_cache_control; proxy_no_cache $http_cache_control; proxy_pass http://backend; } }
|
🔧 日志配置优化
访问日志优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time $upstream_response_time';
log_format detailed '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time $upstream_response_time ' '$upstream_addr $upstream_status';
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
location ~* \.(jpg|jpeg|png|gif|css|js|ico|woff|woff2)$ { access_log off; log_not_found off; }
|
错误日志优化
1 2 3 4 5 6 7
| error_log /var/log/nginx/error.log warn;
location /api { error_log /var/log/nginx/api_error.log info; }
|
🚀 系统级优化
Linux内核参数优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
net.core.somaxconn = 65535 net.ipv4.tcp_max_syn_backlog = 8192 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_rmem = 4096 87380 67108864 net.ipv4.tcp_wmem = 4096 65536 67108864 net.core.rmem_max = 67108864 net.core.wmem_max = 67108864
fs.file-max = 2097152
net.ipv4.ip_local_port_range = 1024 65535 net.core.netdev_max_backlog = 16384
|
应用配置后生效
1 2 3 4 5
| sudo sysctl -p
sudo sysctl -a
|
📈 性能监控
状态监控配置
1 2 3 4 5 6 7 8 9 10 11 12 13
| server { listen 80; server_name status.example.com;
location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; allow 192.168.1.0/24; deny all; } }
|
性能分析工具
1 2 3 4 5 6 7 8
| ab -n 10000 -c 100 http://example.com/
wrk -t12 -c400 -d30s http://example.com/
|
🛡️ 安全加固清单
✅ 基础安全配置
✅ 高级安全配置
📝 生产环境配置示例
完整的生产级配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| user nginx; worker_processes auto; worker_cpu_affinity 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;
log_format main '$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 main buffer=32k flush=5s;
sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 30; keepalive_requests 100; reset_timedout_connection on;
gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss;
server_tokens off; client_max_body_size 10m; limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; limit_conn_zone $binary_remote_addr zone=addr:10m;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }
|
🔧 故障排查
常见性能问题
| 问题 |
原因 |
解决方案 |
| 连接数不足 |
worker_connections 太低 |
增加到 4096 或更高 |
| CPU使用率高 |
worker_processes 不合理 |
设置为 auto 或 CPU核心数 |
| 响应慢 |
没有启用缓存 |
配置 proxy_cache |
| 内存占用高 |
缓冲区设置过大 |
调整 buffer 参数 |
调优建议
- 逐步调优:一次只调整一个参数,观察效果
- 监控指标:使用监控工具跟踪性能变化
- 压力测试:在测试环境验证配置效果
- 日志分析:定期分析访问和错误日志
- 定期维护:清理旧日志,检查配置文件
🔗 相关资源
学习资源
💡 实践建议
[success] 优化建议
- 先在测试环境验证所有配置
- 逐步优化,一次调整一个参数
- 使用监控工具跟踪性能指标
- 定期备份配置文件
- 建立配置版本管理
下一步:继续学习 04_Nginx实战配置示例_项目部署