Nginx高性能配置详解


Nginx高性能配置详解

Nginx是目前最流行的Web服务器和反向代理,以其高性能、低内存消耗和丰富的功能而闻名。正确的配置可以让Nginx发挥出最大的性能,本文将介绍Nginx的关键配置优化策略。

一、基础性能优化

worker_processes auto;           # 自动匹配CPU核心数
worker_rlimit_nofile 65535;     # 提高文件描述符限制

events {
    worker_connections 4096;     # 每个worker的连接数
    use epoll;                   # Linux使用epoll
    multi_accept on;             # 同时接受所有新连接
}

http {
    sendfile on;                 # 零拷贝传输
    tcp_nopush on;               # 优化数据包发送
    tcp_nodelay on;              # 禁用Nagle算法
    
    # 连接保持
    keepalive_timeout 65;
    keepalive_requests 100000;
    
    # 压缩传输
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types
        text/plain
        text/css
        application/json
        application/javascript
        text/xml
        application/xml;
}

二、反向代理与负载均衡

# 负载均衡配置
upstream backend {
    least_conn;                 # 最少连接策略
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 backup;
    
    keepalive 32;              # 保持长连接
}

server {
    listen 80;
    server_name api.example.com;
    
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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_connect_timeout 5s;
        proxy_send_timeout 10s;
        proxy_read_timeout 30s;
    }
}

三、静态文件缓存

server {
    listen 80;
    server_name static.example.com;
    root /var/www/static;
    
    # 开启etag
    etag on;
    
    # 静态资源长缓存
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        access_log off;
    }
    
    # HTML文件短缓存
    location ~* \.html$ {
        expires 1h;
        add_header Cache-Control "public";
    }
    
    # 禁止缓存API响应
    location /api/ {
        add_header Cache-Control "no-store, no-cache, must-revalidate";
    }
}

四、HTTPS与安全配置

server {
    listen 443 ssl http2;
    server_name example.com;
    
    ssl_certificate /etc/ssl/certs/example.pem;
    ssl_certificate_key /etc/ssl/private/example.key;
    
    # SSL优化
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;
    
    # 只使用TLS 1.2和1.3
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;
    
    # 安全头
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
}

Nginx的配置优化是一个系统工程,需要根据实际场景和流量特点进行调整。建议在调整配置后使用压测工具(如wrk、ab)进行性能测试,找到最优的配置参数组合。


0.052729s