CentOS PHP网络传输优化实操指南
一 系统网络与内核参数优化
示例 sysctl 配置(写入 /etc/sysctl.conf 后执行 sysctl -p):
# 队列与回收
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
# 仅在 NAT/同机回源场景启用,跨机房/多路径不建议
# net.ipv4.tcp_tw_recycle = 1
# Keepalive
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_keepalive_intvl = 10
net.ipv4.tcp_keepalive_probes = 6
# 缓冲区(按带宽与RTT调优,示例为通用加大)
net.core.rmem_default = 16777216
net.core.wmem_default = 16777216
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_mem = 65536 393216 524288
# 延迟与加速
net.ipv4.tcp_nodelay = 1
net.ipv4.tcp_fastopen = 3
# 可选:SYN Cookie 抗洪(攻击时启用)
# net.ipv4.tcp_syncookies = 1
文件描述符限制(示例为 /etc/security/limits.conf):
* soft nofile 65536
* hard nofile 65536
说明与依据:上述队列、Keepalive、缓冲区、tcp_nodelay、tcp_fastopen、文件描述符等调优项可显著提升并发连接处理与传输效率,适用于高并发与长肥管道场景。
二 Web与PHP-FPM传输层优化
示例 Nginx 关键配置:
# 启用 HTTP/2(需 TLS)
listen 443 ssl http2;
ssl_certificate /path/fullchain.pem;
ssl_certificate_key /path/privkey.pem;
# 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 静态资源与长连接
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
keepalive_timeout 65;
keepalive_requests 1000;
示例 PHP-FPM(/etc/php-fpm.d/www.conf 片段):
[www]
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
request_terminate_timeout = 30s
slowlog = /var/log/php-fpm/slow.log
request_slowlog_timeout = 10s
说明与依据:HTTP/2、压缩、OPcache、PHP-FPM 进程与连接优化、静态资源与长连接均是提升 PHP 应用网络传输性能的关键手段。
三 应用层传输策略
示例 PHP 响应头设置缓存:
header("Cache-Control: max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
说明与依据:HTTP 缓存、Gzip 压缩与 CDN 是应用层最“性价比高”的传输优化措施。
四 带宽与流量治理
示例 tc 限速(限制 eth0 上 100Mbit/s):
tc qdisc add dev eth0 root tbf rate 100mbit burst 32kbit latency 400ms
说明与依据:tc 限速、防火墙策略、DNS 优化、多线路与实时监控能有效治理带宽占用并提升稳定性。
五 验证与回退
风险提示:内核与网络参数改动可能影响稳定性与安全性;生产环境务必先在测试环境验证,并准备快速回滚方案。