温馨提示×

如何优化debian nginx

小樊
49
2026-09-27 17:50:24
栏目: 智能运维

优化 Debian 上的 Nginx,可以从系统层、Nginx 配置、安全、缓存、监控几个维度来做。下面给你一份比较实用、可落地的优化清单(适合生产环境)。


一、系统层面优化(Debian)

1. 调整 Linux 内核参数

编辑 /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

2. 提高文件描述符限制

编辑 /etc/security/limits.conf:

* soft nofile 100000
* hard nofile 100000

Nginx 用户示例(www-data):

www-data soft nofile 100000
www-data hard nofile 100000

二、Nginx 核心配置优化

配置文件:/etc/nginx/nginx.conf

1. Worker 进程与连接数

worker_processes auto;

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

2. 基础性能参数

worker_rlimit_nofile 100000;

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 30;
    keepalive_requests 1000;
}

三、静态资源 & 缓存优化

1. 开启 Gzip

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;

2. 浏览器缓存

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
    expires 30d;
    access_log off;
}

四、HTTPS & 安全优化(强烈推荐)

1. 使用现代 SSL 配置

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;

2. 安全头

add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header Strict-Transport-Security "max-age=31536000" always;

五、反向代理 & PHP 优化(如适用)

1. 反向代理

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;
}

2. PHP-FPM

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

六、日志与监控

1. 减少日志量

access_log off;  # 静态资源
log_format main '$remote_addr - $request_time';

2. 监控工具

  • nginx -t 检查配置
  • htop, netdata
  • Prometheus + nginx-exporter

七、Debian 专属建议

# 使用官方或稳定源
apt update && apt upgrade -y

# 开启 systemd 限制
systemctl edit nginx
[Service]
LimitNOFILE=100000

八、常见性能误区

❌ 盲目开 worker_connections 100000
❌ 不配置 sendfile
❌ HTTPS 不缓存 session
❌ 开太多 worker_processes


如果你愿意,可以告诉我:

  • 是 静态站 / 接口 / 视频 / 高并发
  • 是否有 SSL / 反向代理 / PHP
  • 当前 QPS 或服务器配置

我可以给你一份针对性 Nginx 配置模板。

0 踩