Nginx高性能配置与安全加固指南


Nginx高性能配置与安全加固指南

Nginx是全球使用最广泛的Web服务器和反向代理服务器,超过三分之一的网站使用Nginx提供服务。正确的Nginx配置不仅能大幅提升网站性能,还能有效防范各种网络攻击。本文将详细介绍Nginx的性能优化配置和安全加固方法。

一、基础性能优化

# nginx.conf 主配置
worker_processes auto;              # 自动匹配CPU核心数
worker_cpu_affinity 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;
    
    # 连接保持
    keepalive_timeout 65;
    keepalive_requests 100000;
    
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 1024;
    gzip_types
        text/plain
        text/css
        application/json
        application/javascript
        text/xml
        application/xml
        image/svg+xml;
    
    # 缓冲区优化
    client_body_buffer_size 16K;
    client_header_buffer_size 1k;
    client_max_body_size 10m;
    large_client_header_buffers 4 8k;

二、SSL/TLS安全配置

server {
    listen 443 ssl http2;
    server_name example.com;
    
    # 证书配置
    ssl_certificate /etc/ssl/certs/example.com.pem;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    
    # 仅使用安全的加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers on;
    
    # SSL会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    
    # OCSP装订
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    
    # HSTS - 强制HTTPS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

# HTTP强制跳转HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

三、安全响应头

server {
    # 防止MIME类型嗅探
    add_header X-Content-Type-Options "nosniff" always;
    
    # XSS保护
    add_header X-XSS-Protection "1; mode=block" always;
    
    # 点击劫持保护
    add_header X-Frame-Options "SAMEORIGIN" always;
    
    # 内容安全策略
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;
    
    # 推荐人策略
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # 权限策略
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
}

四、访问控制与限流

# 限流配置
http {
    # 基于IP的请求限流
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
    
    # 基于IP的连接限流
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
    
    server {
        # API限流
        location /api/ {
            limit_req zone=api_limit burst=20 nodelay;
            limit_req_status 429;
            limit_conn conn_limit 10;
        }
        
        # 禁止访问敏感文件
        location ~ /.(git|env|htaccess) {
            deny all;
            return 404;
        }
        
        # IP白名单
        location /admin/ {
            allow 192.168.1.0/24;
            allow 10.0.0.1;
            deny all;
            proxy_pass http://backend;
        }
        
        # 防止常见攻击
        if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|PATCH)$) {
            return 405;
        }
    }
}

五、PHP-FPM优化

# PHP-FPM配置优化
location ~ .php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    
    # FastCGI缓冲
    fastcgi_buffering on;
    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 32k;
    
    # FastCGI缓存
    fastcgi_cache_path /var/cache/nginx/php levels=1:2
                       keys_zone=phpcache:100m inactive=60m;
    fastcgi_cache phpcache;
    fastcgi_cache_valid 200 301 302 10m;
    fastcgi_cache_use_stale error timeout updating;
    add_header X-Cache-Status $upstream_cache_status;
}

六、静态资源缓存

# 静态资源长期缓存
location ~* .(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
    access_log off;
    
    # 开启文件缓存
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
}

# 禁止缓存动态内容
location ~ .php$ {
    add_header Cache-Control "no-cache, no-store, must-revalidate";
    add_header Pragma "no-cache";
}

Nginx的配置调优是一个持续的过程,需要根据实际的服务器硬件、网络条件和业务需求不断调整。建议在修改配置后使用nginx -t检查语法,使用ab或wrk工具进行压力测试,观察性能变化。同时定期检查Nginx的访问日志和错误日志,及时发现和解决潜在问题。


0.080294s