插件窝 干货文章 nginx优化怎么设置

nginx优化怎么设置

Nginx 优化 连接 cache 284    来源:    2025-04-07

Nginx 作为高性能的 Web 服务器和反向代理,通过合理的优化可以显著提升性能。以下是从基础到进阶的优化方案,分为核心参数、协议优化、资源优化和安全加固四个部分:


一、核心参数优化

  1. 工作进程与连接数

    worker_processes auto;  # 自动匹配CPU核心数
    worker_rlimit_nofile 65535; # 每个worker能打开的最大文件描述符数
    
    events {
       worker_connections 4096;  # 单个worker最大连接数
       use epoll;  # Linux高性能事件模型
       multi_accept on;  # 一次accept多个连接
    }
    
  2. 高效I/O模型

    sendfile on;  # 零拷贝传输静态文件
    tcp_nopush on;  # 合并数据包再发送(需sendfile启用)
    tcp_nodelay on;  # 禁用Nagle算法(高实时性场景)
    

二、协议与传输优化

  1. HTTP/2 与 Gzip

    http {
       gzip on;
       gzip_comp_level 5;
       gzip_min_length 256;
       gzip_types text/plain text/css application/json;
    
       server {
           listen 443 ssl http2;  # 启用HTTP/2
           ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';  # 高性能加密套件
           ssl_session_cache shared:SSL:10m;
           ssl_session_timeout 1h;
       }
    }
    
  2. Keepalive 长连接

    keepalive_timeout 65;  # 客户端长连接保持时间
    keepalive_requests 1000;  # 单个连接最大请求数
    

三、静态资源与缓存优化

  1. 静态文件缓存

    location ~* \.(jpg|css|js)$ {
       expires 365d;  # 浏览器缓存时间
       access_log off;  # 关闭日志减少IO
       add_header Cache-Control "public";
    }
    
  2. 代理缓存(反向代理场景)

    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    location / {
       proxy_cache my_cache;
       proxy_cache_valid 200 302 10m;
    }
    

四、安全与限流

  1. 基础防护

    server_tokens off;  # 隐藏Nginx版本号
    client_max_body_size 10m;  # 限制上传文件大小
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;  # 请求限流
    
  2. 防DDoS配置

    location / {
       limit_req zone=req_limit burst=20 nodelay;
       limit_conn addr 10;  # 单个IP最大连接数
    }
    

五、操作系统级配合优化

  1. 内核参数调整(/etc/sysctl.conf)

    net.core.somaxconn = 65535
    net.ipv4.tcp_max_syn_backlog = 65536
    net.ipv4.tcp_tw_reuse = 1  # 快速回收TIME_WAIT连接
    
  2. 文件描述符限制(/etc/security/limits.conf)

    * soft nofile 65535
    * hard nofile 65535
    

六、监控与调试

  1. 启用状态页

    location /nginx_status {
       stub_status on;
       allow 127.0.0.1;
       deny all;
    }
    
  2. 日志优化

    access_log /var/log/nginx/access.log combined buffer=32k flush=5s;
    error_log /var/log/nginx/error.log warn;
    

优化效果验证工具

  • 压测工具:ab -n 10000 -c 500 http://example.com/
  • 性能分析:nginx -T(检查配置)、ss -lntp(查看连接状态)
  • 监控工具:Prometheus + Grafana(配合nginx-exporter)

注意事项

  1. 根据实际硬件(CPU/内存)调整worker_processesworker_connections
  2. 动态内容(如PHP/Python)需结合FastCGI缓存优化
  3. 生产环境每次修改后执行 nginx -t 测试配置语法

通过以上优化,Nginx可轻松应对万级并发请求(取决于服务器硬件)。建议逐步调整并监控效果,避免过度优化导致资源浪费。