在 Ubuntu 上对 Apache 进行优化,通常可以从 系统层面、Apache 配置、模块精简、缓存与压缩、安全与连接数 几个方面入手。下面给你一套实用、可落地的优化方案。
编辑 /etc/sysctl.conf:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
fs.file-max = 100000
执行:
sysctl -p
编辑 /etc/security/limits.conf:
* soft nofile 65535
* hard nofile 65535
apache2ctl -V | grep MPM
Ubuntu 默认通常是:
sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2
编辑:
/etc/apache2/mods-enabled/mpm_event.conf
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 10000
</IfModule>
根据内存调整:
- 2G 内存:
MaxRequestWorkers 150- 4G+:
300–500
apache2ctl -M
sudo a2dismod autoindex status cgi negotiation userdir
sudo systemctl restart apache2
只保留你真正用到的模块(如 rewrite、ssl、headers)。
sudo a2enmod deflate
编辑 /etc/apache2/mods-enabled/deflate.conf:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css application/javascript
AddOutputFilterByType DEFLATE application/json
</IfModule>
sudo a2enmod expires headers
示例:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 30 days"
ExpiresByType text/css "access plus 7 days"
ExpiresByType application/javascript "access plus 7 days"
</IfModule>
编辑:
/etc/apache2/conf-enabled/keepalive.conf
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
高并发场景:
KeepAliveTimeout 2–5更合适
sudo apt install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php-fpm
sudo systemctl restart apache2
PHP-FPM 比 mod_php 更稳定、更省内存。
在虚拟主机中:
<Directory /var/www/html>
AllowOverride None
</Directory>
把规则写进 Apache 配置,而不是 .htaccess
CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
SetEnvIf Request_URI "\.(jpg|png|css|js)$" dontlog
ServerTokens Prod
ServerSignature Off
LimitRequestBody 10485760
top
htop
apache2ctl -S
ab -n 1000 -c 100 http://localhost/
✅ Ubuntu 22.04
✅ Apache + mpm_event
✅ PHP-FPM
✅ Gzip + Expires
✅ 禁用 .htaccess
✅ 精简模块
如果你愿意,可以告诉我:
我可以直接给你 一份可复制的优化配置。