Apache優化CentOS服務器響應的關鍵策略
/etc/httpd/conf/httpd.conf
中設置:KeepAlive On
(啟用)、MaxKeepAliveRequests 100
(單連接最大請求數)、KeepAliveTimeout 5
(連接超時時間,避免長期占用資源)。prefork
,高并發推薦event
/worker
)。
<IfModule mpm_prefork_module>
StartServers 5 # 啟動時的進程數
MinSpareServers 5 # 最小空閑進程數
MaxSpareServers 10 # 最大空閑進程數
MaxRequestWorkers 150 # 最大并發請求數(根據內存調整,每進程約消耗10-20MB)
MaxConnectionsPerChild 1000 # 每個進程處理請求上限(防止內存泄漏)
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 256
MaxConnectionsPerChild 0
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 30 days"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType application/javascript "access plus 30 days"
</IfModule>
這會讓瀏覽器緩存這些資源,降低服務器負載。<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
支持gzip壓縮,提升頁面加載速度。/etc/sysctl.conf
優化網絡性能,關鍵參數如下:net.ipv4.tcp_fin_timeout = 30 # TIME_WAIT狀態超時時間(秒)
net.ipv4.tcp_tw_reuse = 1 # 允許復用TIME_WAIT套接字
net.ipv4.tcp_max_syn_backlog = 8192 # SYN隊列長度(應對高并發連接請求)
net.ipv4.ip_local_port_range = 1024 65000 # 客戶端可用端口范圍
net.core.somaxconn = 65535 # 監聽隊列最大長度
執行sysctl -p
使配置生效。LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/apache2/mod_cache_disk" # 緩存目錄
CacheEnable disk / # 對根路徑啟用磁盤緩存
CacheDirLevels 2 # 緩存目錄層級
CacheDirLength 1 # 目錄名長度
</IfModule>
</IfModule>
創建緩存目錄并授權:mkdir -p /var/cache/apache2/mod_cache_disk && chown apache:apache /var/cache/apache2/mod_cache_disk
。CustomLog logs/access_log common
(使用簡潔格式)、LogLevel warn
(僅記錄警告及以上級別日志)。mod_cgi
、mod_status
),減少內存消耗。編輯httpd.conf
,注釋對應行:# LoadModule cgi_module modules/mod_cgi.so
。/etc/security/limits.conf
,增加系統可打開文件數:* soft nofile 65535
* hard nofile 65535
臨時生效:ulimit -n 65535
。