Nginx 配置详解:从入门到高性能优化

Nginx 配置详解:从入门到高性能优化

Nginx 是世界上最流行的 Web 服务器之一,全球超过 30% 的网站使用 Nginx 提供服务。本文从基础配置到高性能优化,系统讲解 Nginx 的核心配置项和最佳实践。

一、Nginx 架构原理

Nginx 采用事件驱动、异步非阻塞架构:一个 Master 进程管理多个 Worker 进程,每个 Worker 以单线程运行,使用 epoll(Linux)处理成千上万个并发连接。这使得 Nginx 在高并发场景下内存占用极低,远优于传统的多线程/多进程模型(Apache)。

二、配置文件结构

worker_processes auto;          # Worker进程数(建议等于CPU核心数)
events {
    worker_connections 10240;   # 每个Worker最大连接数
    use epoll;                  # 使用epoll事件模型(Linux)
}
http {
    include mime.types;
    sendfile on;                # 零拷贝文件传输
    tcp_nopush on;              # 与sendfile配合减少报文数量
    keepalive_timeout 65;       # 长连接超时时间
    gzip on;                    # 开启压缩
    
    server {
        listen 80;
        server_name example.com;
        root /var/www/html;
        index index.html;
        
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

三、反向代理配置

upstream backend {
    least_conn;
    server 127.0.0.1:8080 weight=3;
    server 127.0.0.1:8081 weight=1;
    keepalive 32;               # 保持长连接到后端
}
location /api/ {
    proxy_pass http://backend;
    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 10s;
    proxy_read_timeout 60s;
    proxy_next_upstream error timeout http_500 http_502 http_503;
}

四、HTTPS 配置

server {
    listen 443 ssl http2;
    server_name example.com;
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    add_header Strict-Transport-Security "max-age=31536000" always;
}
# HTTP 跳转 HTTPS
server {
    listen 80;
    return 301 https://$host$request_uri;
}

五、静态资源缓存

location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
    access_log off;             # 静态资源不记录访问日志
}

六、限流防护

http {
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}
location /api/ {
    limit_req zone=api_limit burst=20 nodelay;
    limit_conn conn_limit 10;
}

七、性能优化关键配置

  • worker_processes auto:自动等于 CPU 核心数
  • worker_rlimit_nofile 65535:提升文件描述符限制
  • sendfile on:零拷贝传输,提升文件传输效率
  • tcp_nodelay on:禁用 Nagle 算法,降低延迟
  • open_file_cache max=10000 inactive=30s:缓存文件句柄,减少磁盘 IO

总结

Nginx 的强大之处在于配置的灵活性和极致的性能。掌握反向代理、负载均衡、SSL 配置、限流防护这几个核心场景,基本能应对 80% 的生产需求。遇到性能瓶颈时,从 Worker 配置、连接数限制、缓存策略三个维度入手排查。

发表评论