插件窝 干货文章 Nginx虚拟主机优化配置,提升网站性能

Nginx虚拟主机优化配置,提升网站性能

优化 配置 server worker 276    来源:    2025-04-16

以下是为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';
}

四、HTTP/2优化

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;
}

六、实施建议

  1. 压测验证:使用wrkjmeter测试配置前后QPS变化 bash wrk -t4 -c1000 -d30s https://example.com
  2. 灰度发布:先对测试环境配置,观察错误日志
  3. 监控指标:重点关注:
    • Requests per second
    • Time per request
    • upstream_response_time

常见问题解决方案

  1. 502错误:检查proxy_buffer_size是否过小
  2. CPU满载:降低worker_connections或启用reuseport
  3. 内存泄漏:限制worker_processes数量

通过以上优化,典型WordPress站点的TTFB可降低40-60%,静态资源加载速度提升3-5倍。建议根据实际业务场景选择性启用配置项。