溫馨提示×

Ubuntu Apache配置中如何優化靜態資源加載

小樊
39
2025-09-03 06:31:20
欄目: 智能運維

在Ubuntu系統中,使用Apache服務器優化靜態資源加載可以通過以下幾個方面來實現:

1. 啟用壓縮

啟用Gzip壓縮可以顯著減少傳輸的數據量,從而加快頁面加載速度。

sudo a2enmod deflate

編輯Apache配置文件(通常是/etc/apache2/apache2.conf/etc/apache2/sites-available/your-site.conf),添加以下內容:

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>

然后重啟Apache服務:

sudo systemctl restart apache2

2. 啟用緩存

通過設置緩存頭,可以讓瀏覽器緩存靜態資源,減少重復請求。

編輯Apache配置文件,添加以下內容:

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
</IfModule>

然后重啟Apache服務:

sudo systemctl restart apache2

3. 使用CDN

將靜態資源放在CDN(內容分發網絡)上可以顯著提高加載速度,因為CDN會將資源緩存到全球各地的服務器上,用戶可以從最近的服務器獲取資源。

4. 啟用KeepAlive

KeepAlive允許瀏覽器在一個TCP連接上發送多個請求,減少了建立和關閉連接的開銷。

編輯Apache配置文件,添加或修改以下內容:

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

然后重啟Apache服務:

sudo systemctl restart apache2

5. 優化圖片

使用適當的圖片格式(如WebP)和壓縮工具(如TinyPNG)來減小圖片文件的大小。

6. 使用HTTP/2

HTTP/2支持多路復用,可以在一個連接上同時發送多個請求,提高了性能。

確保你的Apache版本支持HTTP/2,并在配置文件中啟用它:

LoadModule http2_module /usr/lib/apache2/modules/mod_http2.so

<VirtualHost *:443>
    Protocols h2 http/1.1
    # 其他配置...
</VirtualHost>

然后重啟Apache服務:

sudo systemctl restart apache2

7. 使用緩存控制頭

通過設置緩存控制頭,可以讓瀏覽器緩存靜態資源,減少重復請求。

編輯Apache配置文件,添加以下內容:

<IfModule mod_headers.c>
    <FilesMatch "\.(jpg|jpeg|png|gif|css|js)$">
        Header set Cache-Control "max-age=31536000, public"
    </FilesMatch>
</IfModule>

然后重啟Apache服務:

sudo systemctl restart apache2

通過以上這些方法,你可以顯著提高Ubuntu系統中Apache服務器加載靜態資源的速度。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女