Nginx 常见配置优化:性能调优与安全加固

Nginx 为什么需要优化?

Nginx作为高性能Web服务器,默认配置适合快速启动,但不一定适合你的特定场景。合理的优化能提升性能和安全性

性能优化

1. 开启Gzip压缩

gzip on;
gzip_types text/plain text/css text/javascript application/json application/javascript application/xml image/svg+xml;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_vary on;

2. 配置静态资源缓存

location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}

# 针对HTML不缓存
location ~* \.(html)$ {
    expires -1;
    add_header Cache-Control "no-store, no-cache, must-revalidate";
}

3. 调整worker进程

# 根据CPU核心数配置
worker_processes auto;
worker_connections 1024;

# 优化连接
keepalive_timeout 65;
client_max_body_size 20m;

安全加固

1. 隐藏版本号

server_tokens off;

2. 添加安全响应头

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;

3. 限制请求频率(防CC攻击)

# 在http块中定义
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

# 在location中使用
location / {
    limit_req zone=req_limit burst=20 nodelay;
}

4. 禁止访问敏感文件

location ~ /\.(?!well-known).* {
    deny all;
}

location ~ \.(env|git|log|sql)$ {
    deny all;
}

反向代理优化

location /api/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    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_set_header X-Forwarded-Proto $scheme;
    
    # 连接池和超时设置
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
}

总结

Nginx优化需要根据实际情况逐步调整并测试。先测出瓶颈再针对性优化,不要盲目堆配置。