在 CentOS 上优化 Apache(通常是 httpd),可以从系统层面、Apache 配置、模块、缓存、安全与监控几个方面入手。下面是一套比较实用、可落地的优化思路(以 CentOS 7/8 + Apache 2.4 为例)。
getenforce
# 若为 Enforcing 且不影响业务,可设为 Permissive
setenforce 0
# 永久关闭需修改 /etc/selinux/config
ulimit -n 65535
修改 /etc/security/limits.conf:
* soft nofile 65535
* hard nofile 65535
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
sysctl -p
httpd -V | grep -i mpm
修改 MPM 配置(CentOS 一般在):
/etc/httpd/conf.modules.d/00-mpm.conf
示例(event MPM):
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 10000
</IfModule>
经验值:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
Timeout 60
ServerTokens Prod
ServerSignature Off
a2enmod deflate # CentOS 通常是已编译
配置:
<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>
减少内存与攻击面:
httpd -M
常见可禁用:
ProxyPass /api/ http://127.0.0.1:8080/
ProxyPassReverse /api/ http://127.0.0.1:8080/
CacheEnable disk /
CacheRoot /var/cache/httpd
CustomLog logs/access_log combined env=!dontlog
SetEnvIf Request_URI "\.(jpg|css|js)$" dontlog
/etc/logrotate.d/httpd
<Directory />
AllowOverride None
Require all denied
</Directory>
<Files ".ht*">
Require all denied
</Files>
systemctl status httpd
apachectl -t
ab -n 10000 -c 200 http://localhost/
如果你愿意,可以告诉我:
我可以给你一套直接可用的配置文件。