优化 Debian 上的 Nginx,可以从系统层、Nginx 配置、安全、缓存、监控几个维度来做。下面给你一份比较实用、可落地的优化清单(适合生产环境)。
编辑 /etc/sysctl.conf 或 /etc/sysctl.d/99-nginx.conf:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
fs.file-max = 1000000
应用:
sysctl -p
编辑 /etc/security/limits.conf:
* soft nofile 100000
* hard nofile 100000
Nginx 用户示例(www-data):
www-data soft nofile 100000
www-data hard nofile 100000
配置文件:/etc/nginx/nginx.conf
worker_processes auto;
events {
worker_connections 10240;
use epoll;
multi_accept on;
}
worker_rlimit_nofile 100000;
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
keepalive_requests 1000;
}
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 30d;
access_log off;
}
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header Strict-Transport-Security "max-age=31536000" always;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m;
location / {
proxy_cache mycache;
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
PHP-FPM 建议:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
access_log off; # 静态资源
log_format main '$remote_addr - $request_time';
nginx -t 检查配置htop, netdata# 使用官方或稳定源
apt update && apt upgrade -y
# 开启 systemd 限制
systemctl edit nginx
[Service]
LimitNOFILE=100000
❌ 盲目开 worker_connections 100000
❌ 不配置 sendfile
❌ HTTPS 不缓存 session
❌ 开太多 worker_processes
如果你愿意,可以告诉我:
我可以给你一份针对性 Nginx 配置模板。