如何在Ubuntu上改进Apache配置
sudo apt update && sudo apt upgrade
,确保Apache(apache2
)及依赖包为最新版本,获取性能优化与安全补丁。Apache的MPM(Multi-Processing Module)决定了请求处理方式,需根据服务器用途选择:
/etc/apache2/mods-enabled/mpm_prefork.conf
<IfModule mpm_prefork_module>
StartServers 5 # 启动时的进程数
MinSpareServers 5 # 最小空闲进程数
MaxSpareServers 10 # 最大空闲进程数
MaxRequestWorkers 150 # 最大并发请求数(避免超过内存容量)
MaxConnectionsPerChild 0 # 每个进程处理的请求数(0=无限制,若内存泄漏需设为正数)
</IfModule>
/etc/apache2/mods-enabled/mpm_worker.conf
(worker)或mpm_event.conf
(event)<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25 # 每个子进程的线程数
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
注:启用MPM前需禁用其他MPM(如
sudo a2dismod mpm_prefork
),避免冲突。
通过a2enmod
命令启用常用模块,提升功能与性能:
sudo a2enmod rewrite # URL重写(支持WordPress等CMS)
sudo a2enmod deflate # Gzip压缩(减少传输体积)
sudo a2enmod expires # 缓存控制(静态资源过期时间)
sudo a2enmod cache # 缓存模块(缓存动态/静态内容)
sudo a2enmod cache_disk # 磁盘缓存(存储缓存文件)
sudo systemctl restart apache2
KeepAlive减少TCP握手开销,但过度使用会消耗资源,需平衡:
KeepAlive On # 启用持久连接
MaxKeepAliveRequests 100 # 每个连接最大请求数(避免单个连接占用过久)
KeepAliveTimeout 5 # 空闲连接超时时间(秒,建议5-10秒)
/etc/apache2/mods-enabled/deflate.conf
中添加:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
/etc/apache2/mods-enabled/cache_disk.conf
中配置:<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /static/ # 缓存/static/目录下的文件
CacheRoot /var/cache/apache2/mod_cache_disk
CacheDirLevels 2 # 缓存目录层级
CacheDirLength 1 # 目录名称长度
CacheDefaultExpire 3600 # 默认缓存时间(秒,1小时)
</IfModule>
</IfModule>
减少资源占用与攻击面,运行以下命令查看已启用模块:
apache2ctl -M
禁用不需要的模块(如status
、autoindex
):
sudo a2dismod status autoindex
sudo systemctl restart apache2
/etc/apache2/apache2.conf
中修改LogLevel
(如从info
改为warn
):LogLevel warn
/etc/logrotate.d/apache2
,添加以下内容实现日志按天分割、压缩:/var/log/apache2/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
systemctl reload apache2 >/dev/null 2>&1 || true
endscript
}
/etc/apache2/mods-enabled/status.conf
中配置:<IfModule mod_status.c>
ExtendedStatus On
<Location "/server-status">
SetHandler server-status
Require ip 127.0.0.1 # 仅允许本地访问(生产环境可限制为管理员IP)
</Location>
</IfModule>
访问http://服务器IP/server-status
查看状态(需重启Apache)。top
、htop
、apachetop
(sudo apt install apachetop
)监控CPU、内存、请求速率等指标。sudo ufw allow 'Apache Full' # 允许80(HTTP)和443(HTTPS)端口
sudo ufw enable
/etc/apache2/apache2.conf
中添加:<Directory "/var/www/html/wp-admin">
Order deny,allow
Deny from all
Allow from 192.168.1.100 # 仅允许特定IP访问管理后台
</Directory>
mod_proxy_balancer
将请求分发到多个后端服务器(如backend1.example.com
、backend2.example.com
),提升并发处理能力。sudo apt install certbot python3-certbot-apache
),配置SSLEngine on
、SSLCertificateFile
等参数。完成配置后,重启Apache使更改生效:
sudo systemctl restart apache2