优化 Linux 下 Apache(httpd)配置,通常从性能、安全、资源管理、缓存与压缩几个方面入手。下面按“实用优先”的方式给你一套常见优化方案(以 Apache 2.4 为例)。
Apache 2.4 常见 MPM:
查看当前 MPM:
apachectl -V | grep MPM
切换 MPM(以 CentOS/RHEL 为例):
# 编辑配置
vim /etc/httpd/conf.modules.d/00-mpm.conf
启用 event:
LoadModule mpm_event_module modules/mod_mpm_event.so
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 10000
</IfModule>
说明:
MaxRequestWorkers 控制最大并发MaxConnectionsPerChild 防止内存泄漏Timeout 30
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
说明:
MaxKeepAliveRequests<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css application/javascript
AddOutputFilterByType DEFLATE application/json
</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>
CacheEnable disk /
CacheRoot /var/cache/apache2
减少攻击面和资源占用:
# 查看已加载模块
apachectl -M
禁用示例:
# LoadModule status_module modules/mod_status.so
# LoadModule autoindex_module modules/mod_autoindex.so
ServerTokens Prod
ServerSignature Off
<Directory /var/www/html>
Options -Indexes
AllowOverride All
Require all granted
</Directory>
避免日志拖慢性能:
LogLevel warn
高并发时可:
access_logrotatelogs 分割日志ulimit -n 65535
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
apachectl configtest
systemctl restart httpd
ab(Apache Bench)压测htop / atop 看资源mod_status(开启后访问 /server-status)如果你愿意,我可以:
你目前 Apache 主要跑什么业务?