Nginx性能优化实践
FastCGI配置优化
FastCGI作为连接Web服务器与后端应用的桥梁,通过保持进程常驻内存显著提升响应效率。其核心优势在于避免CGI的重复进程创建,支持分布式部署架构。
关键配置参数说明:
fastcgi_connection_timeout 300; # FastCGI连接超时时间
fastcgi_send_timeout 300; # 请求传输超时时间
fastcgi_read_timeout 300; # 响应接收超时时间
fastcgi_buffer_size 64k; # 首部缓冲区大小
fastcgi_buffers 4 64k; # 响应缓冲区配置
fastcgi_busy_buffers_size 128k; # 繁忙状态缓冲区
fastcgi_temp_file_write_size 128k; # 临时文件写入大小
fastcgi_cache cache_one; # 启用缓存标识
fastcgi_cache_valid 200 302 1h; # 缓存时效规则
fastcgi_cache_key $host$request_uri; # 缓存键生成规则
缓存路径配置示例:
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=cache_one:10m inactive=1d max_size=40g;
典型应用场景配置:
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_cache cache_one;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_use_stale error timeout invalid_header http_500;
}
Gzip压缩优化
启用Gzip压缩可有效减少传输体积,但需权衡CPU资源消耗。建议对文本类内容进行压缩:
gzip on;
gzip_min_length 1k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types text/css text/xml application/javascript;
gzip_vary on;
配置验证示例:
# 检查配置文件
/usr/local/nginx/sbin/nginx -t
# 查看压缩效果
curl -I http://example.com/test.js
HTTP缓存策略
针对静态资源设置合理的缓存策略:
location ~ \.(jpg|jpeg|png)$ {
expires 365d;
access_log off;
}
location ~ \.(js|css)$ {
expires 10d;
add_header Cache-Control "public, max-age=864000";
}
日志管理方案
实现自动化日志切割与清理:
#!/bin/bash
current_date=$(date +%Y%m%d)
mv access.log /var/log/nginx/access_${current_date}.log
mv error.log /var/log/nginx/error_${current_date}.log
tar -czf /var/log/nginx/logs_${current_date}.tar.gz /var/log/nginx/*.log
find /var/log/nginx -type f -mtime +10 -exec rm -f {} \;
日志格式优化示例:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
访问控制机制
实施基于IP的访问限制:
location ~ \.php$ {
allow 192.168.1.0/24;
deny all;
fastcgi_pass unix:/run/php-fpm.sock;
}
防盗链配置示例:
location ~ \.(jpg|gif|png)$ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
rewrite ^(.*) http://example.com/nolink.png last;
}
}
安全防护措施
防止DDoS攻击配置:
limit_conn_zone $binary_remote_addr zone=ip_limit:10m;
limit_conn_zone $server_name zone=server_limit:10m;
location / {
limit_conn ip_limit 10;
limit_rate 1m;
limit_rate_after 50m;
}
自定义错误页面配置:
error_page 404 /404.html;
location = /404.html {
internal;
root /usr/share/nginx/html;
}