Nginx 性能优化与安全配置

Nginx 性能优化与安全配置

ℹ️生产环境 Nginx 性能调优和安全加固最佳实践

🎯 学习目标

  • 掌握 Nginx 性能优化的核心参数
  • 学习生产环境的安全配置策略
  • 了解高并发场景的优化技巧
  • 实战:配置生产级 Nginx 服务器

⚡ 性能优化配置

1️⃣ 工作进程优化

1
2
3
4
5
6
7
8
9
10
11
12
# 根据CPU核心数自动设置工作进程数
worker_processes auto;

# 将每个工作进程绑定到特定的CPU核心
worker_cpu_affinity auto;

# 每个工作进程的最大连接数
events {
worker_connections 4096; # 默认1024,可提升到4096或更高
use epoll; # Linux系统使用epoll事件模型
multi_accept on; # 允许一次接受多个连接
}

2️⃣ 文件描述符限制

1
2
3
4
5
6
# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

# /etc/sysctl.conf
fs.file-max = 2097152

3️⃣ 核心性能参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
http {
# 基础性能优化
sendfile on; # 使用sendfile系统调用
tcp_nopush on; # 数据包累积到一定大小再发送
tcp_nodelay on; # 禁用Nagle算法,减少延迟
keepalive_timeout 30; # 保持连接时间(秒)

# 缓冲区优化
client_body_buffer_size 128k;
client_max_body_size 10m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
output_buffers 1 32k;
postpone_output 1460;

# 连接优化
keepalive_requests 100; # 每个连接最大请求数
reset_timedout_connection on; # 重置超时连接

# 文件缓存
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}

4️⃣ Gzip 压缩配置

1
2
3
4
5
6
7
8
9
10
11
12
# 启用Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;

# 排除不需要压缩的文件类型
gzip_disable "msie6";

🔒 安全配置

1️⃣ 隐藏版本信息

1
2
3
4
5
# 在http块中配置
http {
server_tokens off; # 隐藏Nginx版本号
more_set_headers 'Server: MyWebServer'; # 自定义服务器名称
}

2️⃣ 限制请求大小

1
2
3
4
5
6
7
8
9
10
11
12
# 限制请求体大小,防止DDoS攻击
client_max_body_size 10m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;

# 限制请求速率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_req zone=one burst=20 nodelay;

# 限制连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn addr 10;

3️⃣ SSL/TLS 安全配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
server {
listen 443 ssl http2;
server_name example.com;

# SSL证书配置
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;

# SSL协议和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;

# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/ssl/ca-bundle.crt;

# 安全响应头
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
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;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
}

4️⃣ 访问控制和IP限制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 限制特定路径的访问
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
}

# 阻止特定User-Agent
if ($http_user_agent ~* (wget|curl|scanner) ) {
return 403;
}

# 阻止特定Referer
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}

5️⃣ 防止常见攻击

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 防止SQL注入
if ($args ~* "union.*select.*\(" ) {
return 403;
}

# 防止文件包含攻击
if ($args ~* "php://input" ) {
return 403;
}

# 防止XSS攻击
if ($args ~* "<script>" ) {
return 403;
}

# 限制访问敏感文件
location ~ /\.(htaccess|htpasswd|git|svn) {
deny all;
}

📊 缓存配置优化

静态资源缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}

# HTML文件缓存
location ~* \.html$ {
expires 1h;
add_header Cache-Control "public, must-revalidate";
}

# API响应不缓存
location /api {
expires -1;
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
}

Proxy Cache 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 定义缓存路径和参数
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;

server {
location / {
# 启用代理缓存
proxy_cache my_cache;

# 缓存键配置
proxy_cache_key "$scheme$request_method$host$request_uri";

# 缓存有效期
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;

# 缓存控制头
add_header X-Cache-Status $upstream_cache_status;

# 代理设置
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

# 绕过缓存
location /api {
proxy_cache_bypass $http_cache_control;
proxy_no_cache $http_cache_control;
proxy_pass http://backend;
}
}

🔧 日志配置优化

访问日志优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 自定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';

log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$upstream_addr $upstream_status';

# 访问日志配置
access_log /var/log/nginx/access.log main buffer=32k flush=5s;

# 静态资源不记录日志
location ~* \.(jpg|jpeg|png|gif|css|js|ico|woff|woff2)$ {
access_log off;
log_not_found off;
}

错误日志优化

1
2
3
4
5
6
7
# 错误日志级别:debug, info, notice, warn, error, crit, alert, emerg
error_log /var/log/nginx/error.log warn;

# 特定目录的错误日志
location /api {
error_log /var/log/nginx/api_error.log info;
}

🚀 系统级优化

Linux内核参数优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# /etc/sysctl.conf

# 网络连接优化
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30

# TCP缓冲区优化
net.ipv4.tcp_rmem = 4096 87380 67108864
net.ipv4.tcp_wmem = 4096 65536 67108864
net.core.rmem_max = 67108864
net.core.wmem_max = 67108864

# 文件描述符限制
fs.file-max = 2097152

# 应用优化
net.ipv4.ip_local_port_range = 1024 65535
net.core.netdev_max_backlog = 16384

应用配置后生效

1
2
3
4
5
# 立即生效
sudo sysctl -p

# 查看当前配置
sudo sysctl -a

📈 性能监控

状态监控配置

1
2
3
4
5
6
7
8
9
10
11
12
13
# 编译时添加 stub_status 模块
server {
listen 80;
server_name status.example.com;

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

性能分析工具

1
2
3
4
5
6
7
8
# 使用ab工具进行压力测试
ab -n 10000 -c 100 http://example.com/

# 使用wrk工具
wrk -t12 -c400 -d30s http://example.com/

# 使用nginx-amplify监控
# https://nginx.com/amplify/

🛡️ 安全加固清单

✅ 基础安全配置

  • 隐藏 Nginx 版本信息
  • 限制请求大小和速率
  • 配置 SSL/TLS 安全协议
  • 设置安全响应头
  • 限制敏感文件访问
  • 配置访问控制和IP限制

✅ 高级安全配置

  • 配置防火墙规则
  • 启用 Fail2Ban 防护
  • 配置 HTTPS 强制跳转
  • 实施速率限制
  • 配置日志监控
  • 定期更新 Nginx 版本

📝 生产环境配置示例

完整的生产级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
user nginx;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;

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

events {
worker_connections 4096;
use epoll;
multi_accept on;
}

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" '
'$request_time $upstream_response_time';

access_log /var/log/nginx/access.log main buffer=32k flush=5s;

# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
keepalive_requests 100;
reset_timedout_connection on;

# 压缩配置
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss;

# 安全配置
server_tokens off;
client_max_body_size 10m;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;

# 缓存配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
max_size=1g inactive=60m use_temp_path=off;

# 包含站点配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

🔧 故障排查

常见性能问题

问题 原因 解决方案
连接数不足 worker_connections 太低 增加到 4096 或更高
CPU使用率高 worker_processes 不合理 设置为 auto 或 CPU核心数
响应慢 没有启用缓存 配置 proxy_cache
内存占用高 缓冲区设置过大 调整 buffer 参数

调优建议

  1. 逐步调优:一次只调整一个参数,观察效果
  2. 监控指标:使用监控工具跟踪性能变化
  3. 压力测试:在测试环境验证配置效果
  4. 日志分析:定期分析访问和错误日志
  5. 定期维护:清理旧日志,检查配置文件

🔗 相关资源

学习资源


💡 实践建议

[success] 优化建议

  1. 先在测试环境验证所有配置
  2. 逐步优化,一次调整一个参数
  3. 使用监控工具跟踪性能指标
    1. 定期备份配置文件
    2. 建立配置版本管理

下一步:继续学习 04_Nginx实战配置示例_项目部署