Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Nginx 生产级 nginx.conf

生产级 nginx.conf

下面是一份生产级 nginx.conf 模板,包含 HTTP->HTTPS 强制跳转、HTTP/2、SSL(现代安全配置)、性能优化(worker、连接、缓冲、gzip、keepalive、upstream keepalive)、安全性(HSTS、OCSP、session)以及常用 proxy/fastcgi 设置。配置里带注释,按需替换证书路径、域名和上游服务地址。

注意:不同 Nginx 版本在启用 HTTP/2 的语法上可能略有差别(http2;、http2 on; 或 listen … http2;)。我在示例中使用通用写法 listen 443 ssl; + http2;,如果你当前版本报语法错误,按你环境改为 http2 on; 或 listen 443 ssl http2; 即可(在注释处标明)。

# /etc/nginx/nginx.conf
user  nginx;
worker_processes  auto;                # 推荐 auto,根据 CPU 核心数自动设置
worker_rlimit_nofile 65535;

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

events {
    use epoll;
    worker_connections  4096;         # 每 worker 的最大连接数(可按需调整)
    multi_accept on;
    accept_mutex off;
}

http {
    # 基础
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65s;
    types_hash_max_size 2048;

    server_tokens off;

    # 日志格式
    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;

    # 缓冲与请求限制(可针对 2G 内存/双核适当下调)
    client_max_body_size 20m;
    client_body_buffer_size 64k;
    client_header_buffer_size 8k;
    large_client_header_buffers 4 16k;

    client_body_timeout 20s;
    client_header_timeout 20s;
    send_timeout 20s;

    # Gzip 压缩
    gzip on;
    gzip_http_version 1.1;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_vary on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # SSL 优化(替换为你的证书)
    ssl_session_cache shared:SSL:50m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;

    # 推荐的安全协议与密码套件(支持 TLS1.2/1.3)
    ssl_protocols TLSv1.2 TLSv1.3;
    # 对于 TLS1.3,Cipher 配置由 OpenSSL 控制;下面为 TLS1.2 ciphers
    ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:'
                'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:'
                'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers off;

    # OCSP Stapling(启用后需要正确的 ssl_trusted_certificate)
    resolver 1.1.1.1 8.8.8.8 valid=300s;
    resolver_timeout 5s;

    # 安全头(可按需打开/修改)
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";

    # Limit / rate limiting
    # 每个 IP 允许的并发请求数与速率控制(按需调整)
    limit_conn_zone $binary_remote_addr zone=addr:10m;
    limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s;

    # Upstream 常用示例(添加 keepalive)
    upstream app_backend {
        server 127.0.0.1:8000 max_fails=3 fail_timeout=30s;
        server 127.0.0.1:8001 max_fails=3 fail_timeout=30s;
        keepalive 16;
    }

    # Proxy 默认设置(可 include 到 conf.d/proxy.conf)
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    # include 站点与额外配置
    include /etc/nginx/conf.d/*.conf;
}

示例:生产级 server(HTTP->HTTPS、HTTP/2、SSL、Proxy)

将下面的 server 填入 /etc/nginx/conf.d/site.conf(替换 example.com、证书路径与 upstream)。

server {
    listen 80;
    server_name example.com www.example.com;

    # 强制 HTTPS(带原始请求 URI 与 args)
    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl;           # 若你的 Nginx 要求其它语法(如 `http2 on;`),可替换
    # 启用 HTTP/2;在部分版本需要调整语法为 "http2 on;" 或 "listen 443 ssl http2;"
    http2;

    server_name example.com www.example.com;

    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    # 如果启用 OCSP stapling,需要设置 trusted cert
    ssl_trusted_certificate /etc/ssl/certs/chain.pem;

    # OCSP stapling
    ssl_stapling on;
    ssl_stapling_verify on;

    # 强制 HSTS(慎用,确保 HTTPS 完整可用)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # 缓存静态资源(按需调整)
    location ~* \.(?:css|js|jpg|jpeg|gif|png|svg|ico|webp|woff2?)$ {
        root /var/www/html;   # 替换为你的静态目录
        expires 30d;
        add_header Cache-Control "public";
        access_log off;
        try_files $uri =404;
    }

    # 前端 SPA(例如 /admin/)
    location /admin/ {
        alias /data/websites/default/8000/admin/;
        index index.html;
        # history 模式 fallback 到 index.html
        try_files $uri $uri/ /admin/index.html;
    }

    # 反向代理到 upstream,带常见 header 与超时配置
    location /api/ {
        proxy_pass http://app_backend;
        proxy_set_header Host $host;                    # 推荐 $host(比 $http_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_http_version 1.1;
        proxy_set_header Connection $connection_upgrade;
        proxy_connect_timeout 5s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # proxy buffers
        proxy_buffer_size 16k;
        proxy_buffers 4 32k;
        proxy_busy_buffers_size 64k;

        # 允许将大请求体传给后端(如果需要)
        client_max_body_size 50m;
    }

    # FastCGI PHP 示例(如果有)
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 60s;

        # FastCGI 缓冲区
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
    }

    # 访问日志/错误日志 可单独配置
    access_log /var/log/nginx/example.access.log main;
    error_log /var/log/nginx/example.error.log warn;
}

部署/检查步骤(必做)

  1. 替换上面配置中的域名、证书路径、upstream 地址、静态目录等。

  2. 语法检查:

    nginx -t
    
  3. 重新加载 Nginx:

    systemctl reload nginx
    
  4. 观察日志(错误/访问)验证请求是否按预期转发:

    tail -f /var/log/nginx/error.log /var/log/nginx/access.log
    

小结与调优建议

  • worker_processes auto + worker_connections 配合决定最大并发:max_clients ≈ worker_processes * worker_connections。2 核、2GB 的机器可选 worker_connections 4k~8k(根据内存与应用调整)。
  • 大文件上传场景请谨慎调 client_body_buffer_size(避免大量并发时内存耗尽)。
  • 启用 ssl_session_cache 与 keepalive 能显著降低握手/连接开销。
  • 若使用 HTTP/2/3,注意测试浏览器支持和 Nginx/OpenSSL 版本兼容性。
  • 生产环境建议配置监控(nginx-vts、Prometheus exporter)并做好日志轮转。