以下是优化Ubuntu Apache下PHP性能的关键步骤:
启用OPcache
安装并启用OPcache扩展,编辑/etc/php/{version}/apache2/php.ini,确保以下配置生效:
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
配置PHP-FPM(推荐)
sudo apt install php-fpm/etc/php/{version}/fpm/pool.d/www.conf,调整进程管理参数(如pm.max_children根据服务器内存设置)。mod_proxy_fcgi,配置虚拟主机将PHP请求代理至PHP-FPM:<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php/php{version}-fpm.sock|fcgi://localhost"
</FilesMatch>
优化Apache配置
KeepAlive并调整参数:KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
mod_deflate和mod_expires压缩静态资源并设置缓存:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
</IfModule>
调整PHP配置
memory_limit=256M
max_execution_time=30
使用缓存技术
php.ini加载对应扩展。监控与调优
htop、php-fpm status监控进程状态,调整进程数避免内存溢出。ab(ApacheBench)或New Relic测试性能,定位瓶颈。其他优化
注意:根据服务器资源(内存、CPU)和应用场景调整参数,测试后逐步上线。