Debian Apache调优指南
调优Debian上的Apache服务器需从系统基础、模块管理、MPM配置、缓存优化、并发处理、日志与安全等多维度入手,以下是具体步骤:
sudo apt update && sudo apt upgrade,确保系统内核、Apache及依赖包为最新版本,修复已知漏洞并提升稳定性。apache2ctl -M列出已加载模块,禁用未使用的模块(如authn_file、autoindex等),减少内存占用:sudo a2dismod 模块名 # 如a2dismod authn_file
sudo systemctl restart apache2
```。
sudo a2enmod deflate # Gzip压缩
sudo a2enmod cache # 缓存模块
sudo a2enmod cache_disk # 磁盘缓存
sudo a2enmod expires # 静态资源过期头
sudo a2enmod ssl # HTTPS支持
sudo systemctl restart apache2
```。
AllowOverride None,避免Apache频繁读取.htaccess文件(降低I/O开销)。根据应用类型选择合适的MPM(prefork适用于非线程安全的PHP,event/worker适用于线程安全场景),编辑对应配置文件(如/etc/apache2/mods-enabled/mpm_event.conf):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150 # 根据服务器内存调整(每进程约消耗5-10MB)
MaxConnectionsPerChild 0 # 0表示无限制(避免频繁创建进程)
</IfModule>
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000 # 限制每个子进程处理的请求数(防止内存泄漏)
</IfModule>
注:修改后需重启Apache生效。mod_expires设置静态文件(CSS、JS、图片)的缓存时间,减少重复请求:<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 hour"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
</IfModule>
```。
mod_deflate压缩文本类内容(HTML、CSS、JS),减少传输体积:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
```。
KeepAliveTimeout与服务器负载):KeepAlive On
MaxKeepAliveRequests 100 # 单个连接最大请求数
KeepAliveTimeout 5 # 连接保持时间(秒)
```。
HostnameLookups Off
```。
cronolog分割日志(避免单个日志文件过大):CustomLog "|/usr/bin/cronolog /var/log/apache2/%Y-%m-%d.access.log" combined
ExtendedStatus):ExtendedStatus Off
```。
htop(实时进程)、vmstat 1(系统整体状态)、netstat -tulnp(网络连接)监控服务器负载,及时发现瓶颈。ufw仅开放必要端口(HTTP 80、HTTPS 443):sudo ufw allow 'Apache Full' # 开放80/443端口
sudo ufw enable
```。
sudo apt autoremove && sudo apt cleanrsync或tar定期备份/etc/apache2、网站根目录。mod_php),减少内存占用:sudo apt install php-fpm
sudo a2enconf php-fpm # 启用PHP-FPM配置
sudo systemctl restart apache2
需在虚拟主机中配置ProxyPassMatch指令。/etc/sysctl.conf,优化TCP性能:net.core.somaxconn = 65535 # 最大连接队列长度
net.ipv4.tcp_max_syn_backlog = 65535 # SYN队列长度
net.ipv4.tcp_tw_reuse = 1 # 复用TIME-WAIT连接
net.ipv4.tcp_fin_timeout = 30 # TIME-WAIT超时时间(秒)
运行sudo sysctl -p使配置生效。