以下是LNMP环境下Nginx的调优要点,涵盖配置、系统及性能优化:
工作进程与连接数
worker_processes auto;
// 自动匹配CPU核心数。worker_connections 65535;
// 单个worker最大连接数,需结合系统文件描述符限制。use epoll;
(Linux下高效模型)。静态资源优化
expires 365d;
+ add_header Cache-Control "public";
。gzip on; gzip_types text/css application/javascript;
。动态请求优化(PHP场景)
pm.max_children
(建议CPU核心数×2)、pm.start_servers
。proxy_cache_path
+ proxy_cache_valid
减少后端压力。连接与超时设置
keepalive_timeout 65s;
// 保持长连接,减少握手开销。client_max_body_size 20M;
// 限制上传文件大小。文件描述符限制
ulimit -n 65535
。/etc/security/limits.conf
,设置* soft nofile 65535
。内核参数调优
/etc/sysctl.conf
:net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
sysctl -p
生效。负载均衡
upstream backend { server 10.0.0.1:80; server 10.0.0.2:80; }
。least_conn
算法分配请求。流量控制
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
。limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
。安全加固
server_tokens off;
。location ~ /\.(ht|git) { deny all; }
。日志与监控
access_log /var/log/nginx/access.log buffer=64k flush=5m;
。nginx -t
测试配置语法。ab
或wrk
进行压力测试,观察CPU、内存使用情况。参考来源: