CentOS 上 Apache + PHP 的优化实践
一 架构选择与基础准备
sudo yum install httpd php-fpm -y。mod_proxy、mod_proxy_fcgi、mod_deflate;按需启用缓存与过期模块:mod_cache、mod_expires。sudo systemctl enable --now httpd php-fpm;放行防火墙:sudo firewall-cmd --permanent --add-service=http --add-service=https && sudo firewall-cmd --reload。sudo yum update -y,及时获得安全与性能修复。二 Apache 关键调优
KeepAlive On;建议 MaxKeepAliveRequests 100、KeepAliveTimeout 5(按业务 RTT 微调)。MaxRequestWorkers 150(示例值,需结合内存与压测校准)。StartServers 5、MinSpareServers 5、MaxSpareServers 10。MaxRequestsPerChild 0(不限制生命周期,视内存泄漏情况可改为 10000+)。<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
mod_cache/mod_expires,为静态资源设置合理 Cache-Control 与 Expires 头。三 PHP 与 PHP-FPM 调优
/etc/php.d/opcache.ini 或 php.ini)[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
memory_limit = 128M(示例);max_execution_time = 30;上传相关:upload_max_filesize = 20M、post_max_size = 20M。listen = /run/php-fpm/www.sock(或 127.0.0.1:9000);user = apache、group = apache。pm = dynamic;pm.max_children = 50、pm.start_servers = 5、pm.min_spare_servers = 5、pm.max_spare_servers = 35;request_terminate_timeout = 30s。<FilesMatch \.php$>
SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
如使用 Unix Socket,可写为:SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost/var/www/html"。四 数据库与缓存层优化
SELECT *,优化慢查询;合理设置连接池与超时;必要时使用持久连接降低握手开销。五 监控、压测与迭代
BusyWorkers、IdleWorkers、请求耗时等;结合 top/htop、vmstat、iostat 定位 CPU、内存、I/O 瓶颈。wrk 进行基准测试,围绕 MaxRequestWorkers、pm.max_children、KeepAliveTimeout 等参数迭代;逐步加压并观察错误率、P95/P99 延迟与内存占用。