插件窝 干货文章 Linux系统下如何优化nginx

Linux系统下如何优化nginx

Nginx 优化 FastCGI cache 63    来源:    2025-04-26

Nginx 在 Linux 系统下的优化指南

1. 系统级优化

1.1 内核参数调整

# 编辑/etc/sysctl.conf
echo "net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_keepalive_time = 120
net.ipv4.tcp_fin_timeout = 30
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 262144
net.ipv4.tcp_max_orphans = 262144
net.ipv4.tcp_max_syn_backlog = 262144" >> /etc/sysctl.conf

# 使配置生效
sysctl -p

1.2 文件描述符限制

# 编辑/etc/security/limits.conf
echo "* soft nofile 65535
* hard nofile 65535" >> /etc/security/limits.conf

# 对于systemd系统
mkdir -p /etc/systemd/system/nginx.service.d
echo "[Service]
LimitNOFILE=65535" > /etc/systemd/system/nginx.service.d/limits.conf
systemctl daemon-reload

2. Nginx配置优化

2.1 主配置文件优化

user nginx;
worker_processes auto;  # 自动根据CPU核心数设置
worker_cpu_affinity auto;  # CPU亲和性(自动绑定)
worker_rlimit_nofile 65535;  # 每个worker进程能打开的文件描述符数量

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 65535;  # 每个worker最大连接数
    use epoll;  # 使用epoll事件模型(Linux)
    multi_accept on;  # 一次接受多个连接
}

2.2 HTTP模块优化

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" "$http_x_forwarded_for"';
    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;
    server_tokens off;  # 隐藏Nginx版本号

    # 缓冲区优化
    client_body_buffer_size 16k;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 16k;
    client_max_body_size 20m;

    # 压缩配置
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 4;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";

    # 静态文件缓存
    open_file_cache max=10000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    include /etc/nginx/conf.d/*.conf;
}

2.3 虚拟主机优化示例

server {
    listen 80 reuseport;  # Linux 3.9+支持,减少锁竞争
    server_name example.com;

    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ {
        expires 365d;
        access_log off;
        add_header Cache-Control "public, no-transform";
    }

    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    # 其他优化
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # FastCGI优化(如PHP)
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        # FastCGI缓存
        fastcgi_cache my_cache;
        fastcgi_cache_valid 200 301 302 1h;
        fastcgi_cache_use_stale error timeout invalid_header updating http_500 http_503;
        fastcgi_cache_bypass $no_cache;
        fastcgi_no_cache $no_cache;
        fastcgi_cache_lock on;
        fastcgi_cache_lock_timeout 5s;
    }
}

3. 高级优化技术

3.1 启用HTTP/2

server {
    listen 443 ssl http2;  # 添加http2参数
    server_name example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    # SSL优化配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;
}

3.2 负载均衡优化

upstream backend {
    least_conn;  # 最少连接算法
    server backend1.example.com weight=5;
    server backend2.example.com;
    server backend3.example.com max_fails=3 fail_timeout=30s;

    keepalive 32;  # 保持连接池
}

server {
    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 10s;
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 16k;
        proxy_busy_buffers_size 32k;
    }
}

4. 监控与维护

4.1 状态监控

server {
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

4.2 日志轮转

编辑/etc/logrotate.d/nginx:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

5. 性能测试与验证

安装并运行性能测试工具:

# 安装ab(Apache Benchmark)
sudo apt-get install apache2-utils  # Debian/Ubuntu
sudo yum install httpd-tools        # CentOS/RHEL

# 运行测试
ab -n 10000 -c 100 http://example.com/

通过以上优化措施,可以显著提升Nginx在Linux系统下的性能和稳定性。实际优化时应根据服务器硬件配置和具体应用场景进行调整,并通过监控工具持续观察优化效果。