Nginx 生产环境参数

Nginx 生产环境参数优化指南

一、全局参数优化

  1. 进程和工作连接优化
# nginx.conf 主配置文件

user nginx nginx;  # 指定运行用户和组
worker_processes auto;  # 自动设置为CPU核心数
worker_cpu_affinity auto;  # CPU亲和性(自动绑定)

# 错误日志级别调整
error_log /var/log/nginx/error.log warn;  # warn级别减少日志量

# 进程文件描述符限制
worker_rlimit_nofile 65535;  # 每个worker进程最大文件描述符数

pid /var/run/nginx.pid;
  1. Events 事件模块优化
events {
    # 使用高效的事件模型(Linux推荐epoll,FreeBSD推荐kqueue)
    use epoll;
    
    # 每个worker进程最大连接数
    worker_connections 10240;  # 建议值:worker_rlimit_nofile / worker_processes
    
    # 启用多连接接受
    multi_accept on;  # 一次accept()尽可能多接受连接
    
    # 连接队列大小
    accept_mutex on;  # 启用互斥锁,避免惊群效应
    accept_mutex_delay 500ms;  # 获取锁的等待时间
    
    # Linux特有优化
    epoll_events 512;  # epoll事件数量
}

二、HTTP核心模块优化

  1. 基础性能优化
http {
    # 包含MIME类型
    include mime.types;
    default_type application/octet-stream;
    
    # 开启高效文件传输
    sendfile on;  # 启用sendfile系统调用
    sendfile_max_chunk 512k;  # 每次sendfile调用的最大数据量
    
    # TCP优化
    tcp_nopush on;  # 在sendfile模式下,等待数据包填满再发送
    tcp_nodelay on;  # 禁用Nagle算法,提高实时性
    
    # 重置超时FIN_WAIT连接
    reset_timedout_connection on;
    
    # 文件描述符缓存
    open_file_cache max=10000 inactive=30s;  # 缓存文件元信息
    open_file_cache_valid 60s;  # 缓存有效期
    open_file_cache_min_uses 2;  # 至少访问2次才缓存
    open_file_cache_errors on;  # 缓存错误信息
    
    # DNS解析缓存
    resolver 8.8.8.8 114.114.114.114 valid=300s;
    resolver_timeout 5s;
}
  1. 连接超时优化
http {
    # 客户端连接超时
    client_header_timeout 15s;  # 读取请求头超时
    client_body_timeout 15s;    # 读取请求体超时
    send_timeout 30s;           # 发送响应超时
    
    # 长连接优化
    keepalive_timeout 75s;      # 客户端连接保持时间
    keepalive_requests 1000;    # 一个长连接处理的最大请求数
    
    # 限制请求体大小
    client_max_body_size 50m;
    client_body_buffer_size 16k;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 8k;
    
    # 请求限流
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
}

三、缓冲和缓存优化

  1. 代理缓冲优化
http {
    # 代理缓冲区优化
    proxy_buffering on;  # 启用响应缓冲
    proxy_buffer_size 8k;  # 从后端服务器接收的响应头缓冲区大小
    proxy_buffers 32 8k;  # 响应内容缓冲区(数量 大小)
    proxy_busy_buffers_size 16k;  # 繁忙时缓冲区大小
    proxy_temp_file_write_size 16k;  # 临时文件写入大小
    
    # 禁用某些大文件的缓冲
    proxy_request_buffering off;  # 对上传大文件时有用
    
    # 临时文件路径
    proxy_temp_path /var/cache/nginx/proxy_temp 1 2;
    proxy_cache_path /var/cache/nginx/proxy_cache 
                     levels=1:2 
                     keys_zone=cache_zone:100m 
                     inactive=7d 
                     max_size=10g;
}
  1. 压缩优化
http {
    # 启用Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_proxied any;  # 为所有代理请求启用压缩
    gzip_comp_level 6;  # 压缩级别(1-9,6是平衡点)
    gzip_min_length 1024;  # 最小压缩文件大小
    gzip_buffers 16 8k;  # 压缩缓冲区
    
    # 压缩类型
    gzip_types text/plain 
               text/css 
               text/xml 
               text/javascript 
               application/javascript 
               application/xml 
               application/xml+rss 
               application/json 
               image/svg+xml;
    
    # 禁用旧版本IE压缩
    gzip_disable "MSIE [1-6]\.";
    
    # Brotli压缩(需要nginx支持)
    # brotli on;
    # brotli_comp_level 6;
    # brotli_types text/plain text/css text/xml application/javascript application/xml+rss application/json;
}

四、SSL/TLS优化

http {
    server {
        listen 443 ssl http2;
        
        # SSL证书配置
        ssl_certificate /etc/nginx/ssl/server.crt;
        ssl_certificate_key /etc/nginx/ssl/server.key;
        
        # 协议和密码套件优化
        ssl_protocols TLSv1.2 TLSv1.3;  # 禁用旧协议
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
        ssl_prefer_server_ciphers off;  # 现代浏览器推荐关闭
        
        # SSL会话优化
        ssl_session_cache shared:SSL:50m;  # 共享会话缓存
        ssl_session_timeout 1d;  # 会话超时时间
        ssl_session_tickets off;  # 禁用session tickets
        
        # 连接复用(OCSP Stapling)
        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 5s;
        
        # HSTS安全头
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        
        # DH参数(需要生成)
        ssl_dhparam /etc/nginx/ssl/dhparam.pem;
        
        # SSL缓冲区优化
        ssl_buffer_size 4k;
        
        # 启用HTTP/2
        http2_max_field_size 16k;
        http2_max_header_size 32k;
        http2_max_requests 1000;
        http2_max_concurrent_streams 128;
    }
}

五、上游服务器(Upstream)优化

http {
    upstream backend {
        # 负载均衡算法
        least_conn;  # 最少连接数
        
        # 后端服务器配置
        server 192.168.1.101:8080 
               weight=5 
               max_fails=3 
               fail_timeout=30s 
               backup;  # 备份服务器
        
        server 192.168.1.102:8080 
               weight=5 
               max_fails=3 
               fail_timeout=30s;
        
        # 健康检查参数
        keepalive 64;  # 到每个后端服务器的连接池大小
        keepalive_requests 100;  # 每个keepalive连接的最大请求数
        keepalive_timeout 60s;  # keepalive连接超时
    }
    
    # 代理参数优化
    location / {
        proxy_pass http://backend;
        
        # 连接超时
        proxy_connect_timeout 5s;  # 连接后端服务器超时
        proxy_send_timeout 15s;    # 发送请求到后端超时
        proxy_read_timeout 15s;    # 读取后端响应超时
        
        # 重试机制
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_next_upstream_tries 3;  # 最大重试次数
        proxy_next_upstream_timeout 10s;  # 重试超时
        
        # 缓冲优化
        proxy_buffers 16 8k;
        proxy_buffer_size 4k;
        proxy_busy_buffers_size 16k;
        
        # 临时文件
        proxy_temp_file_write_size 64k;
        proxy_max_temp_file_size 1024m;
        
        # 禁用特定情况下的缓冲
        proxy_request_buffering off;
        
        # HTTP版本
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

六、静态文件服务优化

http {
    server {
        # 静态文件缓存优化
        location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ {
            root /var/www/html;
            
            # 缓存控制
            expires 1y;  # 长期缓存
            add_header Cache-Control "public, immutable, max-age=31536000";
            
            # 文件访问优化
            open_file_cache max=1000 inactive=20s;
            open_file_cache_valid 30s;
            open_file_cache_min_uses 2;
            open_file_cache_errors on;
            
            # 关闭访问日志(可选)
            access_log off;
            
            # 预读优化
            # aio on;  # 异步IO,需要内核支持
            # directio 4m;  # 大于4M的文件使用直接IO
            
            # 压缩静态文件
            gzip_static on;  # 使用预压缩的.gz文件
        }
        
        # 大文件下载优化
        location /downloads/ {
            root /var/www;
            
            # 限速
            limit_rate 1m;  # 限制下载速度
            limit_rate_after 10m;  # 10M后开始限速
            
            # 启用断点续传
            mp4;
            flv;
            
            # 禁用缓冲
            proxy_buffering off;
            proxy_request_buffering off;
            
            # 直接IO
            directio 512k;
            output_buffers 1 128k;
        }
    }
}

七、安全优化

http {
    # 隐藏Nginx版本号
    server_tokens off;
    
    # 防止点击劫持
    add_header X-Frame-Options "SAMEORIGIN" always;
    
    # 防止MIME类型嗅探
    add_header X-Content-Type-Options "nosniff" always;
    
    # XSS保护
    add_header X-XSS-Protection "1; mode=block" always;
    
    # 引用策略
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # 内容安全策略
    add_header Content-Security-Policy "default-src 'self';" always;
    
    # 文件上传限制
    client_max_body_size 10m;
    client_body_buffer_size 128k;
    client_body_temp_path /var/tmp/nginx/client_body;
    
    # 请求限流
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    limit_conn_zone $binary_remote_addr zone=addr:10m;
    
    # 屏蔽恶意User-Agent
    if ($http_user_agent ~* (wget|curl|nikto|sqlmap|nmap) ) {
        return 403;
    }
    
    # 限制请求方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
}

八、日志优化

http {
    # 自定义日志格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'urt="$upstream_response_time" cs=$upstream_cache_status';
    
    # 访问日志优化
    access_log /var/log/nginx/access.log main buffer=32k flush=5s;
    
    # 错误日志优化
    error_log /var/log/nginx/error.log warn;
    
    # 日志分割(通过logrotate)
    # 在/etc/logrotate.d/nginx中配置
}

九、系统级优化

  1. Linux内核参数优化
# /etc/sysctl.conf
# 网络参数优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 262144
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 0  # 不建议开启,可能导致NAT问题

# 端口范围
net.ipv4.ip_local_port_range = 1024 65535

# 连接跟踪
net.netfilter.nf_conntrack_max = 655360
net.nf_conntrack_max = 655360

# 内存参数
vm.swappiness = 10
vm.vfs_cache_pressure = 50

# 应用配置
sysctl -p
  1. Nginx进程限制
# /etc/security/limits.conf
nginx soft nofile 65535
nginx hard nofile 65535
nginx soft nproc 65535
nginx hard nproc 65535

十、监控和调试参数

http {
    # 状态页面
    server {
        location /nginx_status {
            stub_status on;
            access_log off;
            allow 127.0.0.1;
            allow 192.168.1.0/24;
            deny all;
        }
        
        # 第三方状态模块
        location /status {
            status;
            allow 127.0.0.1;
            deny all;
        }
    }
    
    # 调试日志(仅在需要时开启)
    # error_log /var/log/nginx/debug.log debug;
}

十一、性能测试建议

# 压力测试
ab -n 100000 -c 1000 http://localhost/

# 长时间测试
siege -c 500 -t 5M http://localhost/

# wrk测试(支持HTTP/2)
wrk -t12 -c400 -d30s http://localhost/

# 监控工具
nginx -t  # 测试配置
strace -p <nginx_pid>  # 系统调用跟踪

配置参考

  1. 基础负载均衡配置
# /etc/nginx/nginx.conf 主配置文件
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 10240;
    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" '
                    '$upstream_addr $upstream_response_time $request_time';
    
    access_log /var/log/nginx/access.log main buffer=32k flush=5s;
    
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;
    types_hash_max_size 2048;
    client_max_body_size 20m;
    
    # 开启gzip
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml;
    
    # 包含负载均衡配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/upstreams/*.conf;
}
  1. 上游服务配置
# /etc/nginx/upstreams/backend.conf
upstream backend_servers {
    # 负载均衡算法(可选:ip_hash, least_conn, hash $key consistent)
    least_conn;  # 最少连接数算法
    
    # 健康检查(需要nginx-plus或使用nginx-upstream-check-module)
    # 或使用 nginx_upstream_check_module
    # check interval=3000 rise=2 fall=3 timeout=1000 type=http;
    
    # 主服务器
    server 10.0.1.101:8080 weight=3 max_fails=2 fail_timeout=30s;
    server 10.0.1.102:8080 weight=3 max_fails=2 fail_timeout=30s;
    server 10.0.1.103:8080 weight=3 max_fails=2 fail_timeout=30s;
    
    # 备用服务器
    server 10.0.2.101:8080 backup;
    server 10.0.2.102:8080 backup;
    
    # 长连接配置
    keepalive 32;  # 每个worker保持的连接数
    keepalive_timeout 60s;
    keepalive_requests 100;
}

# 动态应用服务
upstream app_servers {
    # 会话保持 - 基于IP哈希
    ip_hash;
    
    server 10.0.3.101:8000;
    server 10.0.3.102:8000;
    server 10.0.3.103:8000;
    
    # 会话保持备用方案(应用层session共享时使用least_conn)
    # least_conn;
}

# 静态资源服务
upstream static_servers {
    server 10.0.4.101:80;
    server 10.0.4.102:80;
    
    # 一致性哈希,用于缓存服务器
    hash $request_uri consistent;
}
  1. 应用负载均衡配置
# /etc/nginx/conf.d/app-proxy.conf
server {
    listen 80;
    server_name app.example.com;
    
    # 安全头部
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # 限流配置
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req zone=api burst=20 nodelay;
    
    # 静态资源
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
        proxy_pass http://static_servers;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_cache my_cache;
        proxy_cache_valid 200 304 12h;
        expires 7d;
        access_log off;
    }
    
    # API接口
    location /api/ {
        proxy_pass http://backend_servers;
        
        # 超时配置
        proxy_connect_timeout 5s;
        proxy_send_timeout 10s;
        proxy_read_timeout 30s;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_next_upstream_tries 3;
        
        # 头部传递
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
        
        # 缓冲配置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
        
        # 启用keepalive
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
    
    # WebSocket支持
    location /ws/ {
        proxy_pass http://backend_servers;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
    }
    
    # 健康检查端点
    location /nginx-status {
        stub_status on;
        access_log off;
        allow 10.0.0.0/8;  # 内部网络
        deny all;
    }
    
    # 错误页面
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}
  1. SSL/TLS配置
# /etc/nginx/conf.d/ssl-proxy.conf
server {
    listen 443 ssl http2;
    server_name app.example.com;
    
    # SSL证书
    ssl_certificate /etc/nginx/ssl/app.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/app.example.com.key;
    ssl_trusted_certificate /etc/nginx/ssl/app.example.com.chain.crt;
    
    # SSL协议配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;
    
    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    
    # 重定向HTTP到HTTPS
    if ($scheme = http) {
        return 301 https://$server_name$request_uri;
    }
    
    # 代理配置
    location / {
        proxy_pass http://backend_servers;
        # ... 其他代理配置同上
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容