linux

怎样用Apache2优化图片加载速度

小樊
41
2025-12-10 21:03:05
栏目: 编程语言

Apache2优化图片加载速度的实用方案

一 启用压缩与长缓存

示例配置(建议放入站点或全局配置中):

# 启用压缩(图片可选择性加入)
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/x-javascript text/javascript
    AddOutputFilterByType DEFLATE image/webp
</IfModule>

# 长缓存策略
<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 image/webp "access plus 1 year"
</IfModule>

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

说明:对图片设置 immutable 可避免带文件指纹(如 ?v=)的资源在版本更新时仍被强制回源验证。修改后执行:sudo systemctl restart apache2 使配置生效。

二 启用 HTTP/2 与 KeepAlive

示例配置:

# 在全局或虚拟主机启用 HTTP/2
<IfModule mod_http2.c>
    Protocols h2 http/1.1
</IfModule>

# 启用 KeepAlive
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

修改后执行:sudo systemctl restart apache2 使配置生效。

三 使用 CDN 与源站缓存

示例配置(源站启用磁盘缓存,按需调整):

# 启用磁盘缓存(示例路径,权限与容量请按实际调整)
<IfModule mod_cache_disk.c>
    CacheRoot "/var/cache/apache2/mod_cache_disk"
    CacheEnable disk /
    CacheDirLevels 2
    CacheDirLength 1
</IfModule>

启用后重启服务:sudo systemctl restart apache2。结合 Cache-ControlExpires 能获得更稳定的缓存命中与回源策略。

四 图片本身优化与验证

0
看了该问题的人还看了