优化 Ubuntu 上的 Apache 配置可以从性能、安全、稳定性和可维护性几个方面入手。下面按「常用且安全」的方式给你一套实用清单。
Apache 有几种多处理模块(MPM):
prefork:兼容性好,但占用内存高(适合老 PHP)worker:线程模型,性能更好event:最优(推荐,Ubuntu 默认)查看当前 MPM:
apache2ctl -V | grep -i mpm
切换为 event(如未使用):
sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2
编辑:
sudo nano /etc/apache2/mods-enabled/mpm_event.conf
示例(4GB 内存服务器):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
根据内存调整
MaxRequestWorkers
sudo nano /etc/apache2/apache2.conf
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
sudo a2enmod deflate
在配置中加入:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml 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"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
查看已启用模块:
apache2ctl -M
禁用示例:
sudo a2dismod autoindex status
ServerTokens Prod
ServerSignature Off
<Directory /var/www/html>
Options -Indexes
AllowOverride All
</Directory>
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
开启 HTTP/2:
sudo a2enmod http2
LogLevel warn
使用 logrotate(Ubuntu 默认已配置)
mod_cachephp-fpmsudo apache2ctl configtest
sudo systemctl status apache2
htop
如果你愿意,可以告诉我:
我可以给你针对性配置示例。