以下是为Nginx虚拟主机优化的专业配置方案,从基础配置到高级调优层层递进:
server {
listen 80;
server_name example.com;
# 1. 启用高效传输模式
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 2. 连接超时优化
keepalive_timeout 65;
keepalive_requests 1000;
client_header_timeout 15s;
client_body_timeout 15s;
send_timeout 10s;
# 3. 禁用非必要日志(生产环境)
access_log off;
error_log /var/log/nginx/error.log crit;
# 4. 静态资源处理
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|svg)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
}
# 1. 全局工作进程优化
worker_processes auto; # 自动匹配CPU核心数
worker_rlimit_nofile 100000; # 每个worker能打开的文件描述符数量
events {
worker_connections 4096; # 单个worker最大连接数
multi_accept on; # 同时接受多个新连接
use epoll; # Linux内核下高性能事件模型
}
http {
# 2. MIME类型缓存优化
open_file_cache max=2000 inactive=20s;
open_file_cache_valid 60s;
open_file_cache_min_uses 5;
open_file_cache_errors off;
# 3. Gzip压缩配置
gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_proxied any;
gzip_vary on;
# 4. 反向代理优化
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
# 1. 请求限流(防CC攻击)
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location / {
limit_req zone=req_limit burst=20 nodelay;
}
# 2. 禁用危险方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 3. 隐藏Server头
server_tokens off;
more_clear_headers 'Server';
}
server {
listen 443 ssl http2;
# 1. 启用OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
# 2. 会话复用优化
ssl_session_cache shared:SSL:50m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# 3. 现代加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
}
# 1. 实时状态监控
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
# 2. 使用Prometheus监控
location /metrics {
vhost_traffic_status_display;
vhost_traffic_status_display_format prometheus;
}
wrk
或jmeter
测试配置前后QPS变化
bash
wrk -t4 -c1000 -d30s https://example.com
Requests per second
Time per request
upstream_response_time
proxy_buffer_size
是否过小worker_connections
或启用reuseport
worker_processes
数量通过以上优化,典型WordPress站点的TTFB可降低40-60%,静态资源加载速度提升3-5倍。建议根据实际业务场景选择性启用配置项。