在Ubuntu系統中,使用Apache作為Web服務器時,優化靜態文件服務可以通過以下幾個方面來實現:
緩存可以顯著提高靜態文件的加載速度。
在Apache配置文件中(通常是/etc/apache2/apache2.conf
或/etc/apache2/sites-available/000-default.conf
),添加以下內容:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
使用mod_cache
和mod_cache_disk
模塊來緩存靜態文件。
sudo a2enmod cache
sudo a2enmod cache_disk
然后在配置文件中添加:
<IfModule mod_cache_disk.c>
CacheRoot /var/cache/apache2/mod_cache_disk
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
使用mod_deflate
模塊來壓縮靜態文件,減少傳輸時間。
sudo a2enmod deflate
然后在配置文件中添加:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
確保Gzip壓縮是啟用的。
sudo a2enmod deflate
然后在配置文件中添加:
<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
</IfModule>
如果可能,使用內容分發網絡(CDN)來分發靜態文件,可以顯著提高加載速度和可靠性。
確保靜態文件盡可能小??梢允褂霉ぞ呷?code>imagemin來壓縮圖片,使用UglifyJS
來壓縮JavaScript文件。
啟用KeepAlive可以減少TCP連接的建立和關閉次數,提高性能。
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
根據服務器的內存和CPU資源,調整MaxClients
參數,以控制同時處理請求的客戶端數量。
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
減少日志文件的寫入頻率,可以提高性能。
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined buffer=16k flush=10s
ErrorLog ${APACHE_LOG_DIR}/error.log
如果可能,升級到HTTP/2,它可以顯著提高多路復用和頭部壓縮的效率。
sudo a2enmod http2
然后在配置文件中添加:
Protocols h2 http/1.1
定期重啟Apache服務以應用配置更改并釋放資源。
sudo systemctl restart apache2
通過以上步驟,可以顯著優化Ubuntu系統中Apache服務器的靜態文件服務性能。