优化 Ubuntu 下 Apache2 的配置,通常从 性能、安全、稳定性、可维护性 四个方面入手。下面给你一套实战型优化清单,适合大多数生产环境(中小站点、API、反向代理等)。
Apache 默认加载很多模块,关闭无用模块可减少内存占用。
apache2ctl -M # 查看已加载模块
关闭示例:
sudo a2dismod autoindex cgi status
sudo systemctl restart apache2
常见可关闭模块:
autoindex(目录浏览)cgistatus(公网不建议)userdirUbuntu 默认使用 mpm_event(推荐),不要使用 prefork(除非必须跑 PHP 旧版本)。
查看当前 MPM:
apache2ctl -V | grep MPM
启用 event:
sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2
编辑:
sudo nano /etc/apache2/mods-available/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
编辑:
sudo nano /etc/apache2/apache2.conf
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
ServerTokens Prod
ServerSignature Off
防止泄露 Apache 版本信息。
示例:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
# 开启压缩
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
# 缓存
<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>
# 安全头
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
</VirtualHost>
sudo a2enmod rewrite deflate expires headers ssl
sudo systemctl restart apache2
<Directory /var/www/html>
Options -Indexes
AllowOverride All
Require all granted
</Directory>
sudo apt install certbot python3-certbot-apache
sudo certbot --apache
自动配置 SSL + 自动续期。
LimitRequestBody 10485760 # 10MB
CustomLog /var/log/apache2/access.log combined
ErrorLog /var/log/apache2/error.log
Ubuntu 默认已启用 logrotate,可检查:
cat /etc/logrotate.d/apache2
ulimit -n
如过小,修改:
sudo nano /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
sudo nano /etc/apache2/ports.conf
只保留:
Listen 80
sudo apache2ctl configtest
ab -n 1000 -c 100 http://example.com/
✅ Apache 比 Nginx 慢?
→ 正确配置 MPM + 关闭无用模块后差距不大,但高并发 Nginx 更优。
✅ Apache 占用内存高?
→ 多半是 mpm_prefork + PHP,建议切换 event + PHP-FPM。
✅ Apache2 + mpm_event + PHP-FPM + HTTPS + 缓存头
如果你愿意,可以告诉我:
我可以直接帮你给出一份可直接用的完整配置文件。