在 Ubuntu 上优化 Apache2,通常从性能、并发、安全、系统层面几个角度入手。下面给你一份实用向调优指南(以 Ubuntu 20.04/22.04 为主,Apache 2.4)。
Apache 2.4 常用三种 MPM:
apachectl -V | grep MPM
sudo a2dismod php* mpm_prefork
sudo a2enmod mpm_event proxy_fcgi setenvif
sudo a2enconf php*-fpm
sudo systemctl restart apache2
编辑:
sudo nano /etc/apache2/mods-available/mpm_event.conf
示例(4核8G服务器):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
</IfModule>
通用原则:
MaxRequestWorkers ≈ 内存 / 每进程内存MaxConnectionsPerChild 防止内存泄漏sudo nano /etc/apache2/mods-available/mpm_event.conf
或:
sudo nano /etc/apache2/apache2.conf
推荐:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
太长会占连接,太短会增加握手
查看已启模块:
apache2ctl -M
常见可关:
sudo a2dismod status autoindex cgi negotiation
保留:
sudo a2enmod deflate
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
sudo a2enmod expires
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
</IfModule>
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
net.ipv4.tcp_fin_timeout = 30
sudo sysctl -p
sudo a2enmod http2
虚拟主机中:
Protocols h2 http/1.1
减少磁盘 IO:
CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
或关闭:
sudo a2dismod status
sudo a2enmod headers
ServerTokens Prod
ServerSignature Off
ab -n 1000 -c 100 http://localhost/
或:
wrk -t4 -c100 -d30s http://localhost/
✅ Ubuntu + Apache2
✅ mpm_event
✅ PHP-FPM
✅ HTTP/2
✅ gzip + cache
✅ 合理 MaxRequestWorkers
如果你愿意,可以告诉我:
我可以给你直接可用的配置文件。