以下是CentOS Apache2性能調優的關鍵措施:
啟用KeepAlive
減少連接建立開銷,在/etc/httpd/conf/httpd.conf中設置:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
調整MPM模塊參數
根據服務器資源修改/etc/httpd/conf.modules.d/00-mpm.conf(以prefork為例):
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150 # 根據CPU核心數調整
MaxConnectionsPerChild 0
高并發場景可切換為worker或event模塊(需注釋掉prefork配置)。
靜態文件緩存
通過mod_expires減少磁盤訪問:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType text/css "access plus 30 days"
</IfModule>
啟用壓縮
使用mod_deflate壓縮傳輸數據:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
優化日志記錄
簡化日志格式或降低日志級別:
CustomLog logs/access_log common
LogLevel warn
調整內核參數
修改/etc/sysctl.conf,優化TCP連接和內存管理:
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.core.somaxconn = 1024
vm.swappiness = 10 # 減少內存交換
執行sysctl -p使配置生效。
硬件與文件系統
禁用不必要的模塊
編輯httpd.conf,注釋掉未使用的模塊(如mod_rewrite若無需重寫規則)。
啟用緩存模塊
如mod_cache+mod_disk_cache,緩存動態內容以減輕后端壓力。
top、htop、vmstat等工具監控CPU、內存使用情況。ab(Apache Benchmark)或wrk工具測試并發性能,驗證優化效果。注意:修改配置后需重啟Apache服務(systemctl restart httpd),建議先在測試環境驗證。[1,2,3,4,5,6,7,8,9,10,11]