通过Apache配置实现网站压缩可以显著提高网站的加载速度,减少带宽消耗。以下是详细的步骤和配置示例:
首先,确保Apache启用了以下模块:
mod_deflate:用于压缩文本内容。mod_expires:用于设置资源的过期时间。mod_headers:用于设置HTTP头信息。你可以通过以下命令启用这些模块:
sudo a2enmod deflate
sudo a2enmod expires
sudo a2enmod headers
mod_deflate编辑Apache的配置文件(通常是/etc/apache2/apache2.conf或/etc/httpd/conf/httpd.conf),添加或修改以下配置:
<IfModule mod_deflate.c>
# 启用压缩
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
# 压缩最小长度
DeflateMinLength 256
# 压缩级别
DeflateCompressionLevel 9
# 启用gzip压缩
AddEncoding gzip .gz .tgz .zip .gzip
# 启用brotli压缩
AddEncoding br .br
BrotliCompressionLevel 11
BrotliType text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
mod_expires在同一个配置文件中,添加或修改以下配置:
<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"
# CSS文件
ExpiresByType text/css "access plus 1 month"
# JavaScript文件
ExpiresByType application/javascript "access plus 1 month"
# HTML文件
ExpiresByType text/html "access plus 1 minute"
# JSON文件
ExpiresByType application/json "access plus 1 minute"
</IfModule>
mod_headers在同一个配置文件中,添加或修改以下配置:
<IfModule mod_headers.c>
# 设置缓存控制头
<FilesMatch "\.(html|htm|css|js|json)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
# 设置ETag头
FileETag INode MTime Size
</IfModule>
完成配置后,重启Apache服务器以使更改生效:
sudo systemctl restart apache2
你可以使用浏览器的开发者工具或在线工具(如GTmetrix)来验证压缩是否生效。
通过以上步骤,你可以有效地通过Apache配置实现网站压缩,提升网站的性能和用户体验。