在 Ubuntu 上优化 Apache2 性能,通常可以从 MPA/MPM 配置、模块精简、缓存、系统参数、静态资源、PHP/FPM 等方面入手。下面按「实用优先」给你一套常见优化方案。
Apache 有三种 MPM:
apachectl -V | grep -i mpm
sudo a2dismod php*
sudo a2enmod mpm_event
sudo systemctl restart apache2
编辑:
sudo nano /etc/apache2/mods-enabled/mpm_event.conf
示例(2核4G服务器):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
内存小就降低
MaxRequestWorkers
查看已启用模块:
apache2ctl -M
常见可关闭:
sudo a2dismod autoindex status cgi negotiation userdir
sudo systemctl restart apache2
sudo a2enmod deflate
sudo a2enmod headers
编辑:
sudo nano /etc/apache2/conf-available/deflate.conf
示例:
AddOutputFilterByType DEFLATE text/html text/css application/javascript
sudo a2enconf deflate
sudo systemctl restart apache2
sudo a2enmod expires
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
比 mod_php 快很多。
sudo apt install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php-fpm
sudo a2dismod php*
sudo systemctl restart apache2
高并发短连接可关:
sudo nano /etc/apache2/apache2.conf
KeepAlive Off
或适度:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
ulimit -n
如太小:
sudo nano /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
sudo nano /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
sudo sysctl -p
top
htop
apachectl status
sudo tail -f /var/log/apache2/access.log
✅ event MPM
✅ PHP-FPM
✅ Gzip
✅ 浏览器缓存
✅ 精简模块
✅ 合理 MaxRequestWorkers
如果你愿意,可以告诉我:
我可以给你一套针对性配置。