在 Ubuntu + Apache2 下开启 Gzip(压缩),通常是通过 mod_deflate 模块实现的。下面是完整操作步骤:
Apache2 使用 mod_deflate 来处理 Gzip 压缩。
sudo a2enmod deflate
sudo systemctl restart apache2
编辑配置文件(任选其一):
sudo nano /etc/apache2/apache2.conf
或在 /etc/apache2/sites-enabled/ 中编辑你的站点配置:
sudo nano /etc/apache2/sites-enabled/000-default.conf
在 <VirtualHost> 或全局配置中加入:
<IfModule mod_deflate.c>
# 启用压缩
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/font-woff
AddOutputFilterByType DEFLATE application/font-woff2
AddOutputFilterByType DEFLATE image/svg+xml
# 忽略部分浏览器
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# 不要压缩已压缩的文件
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|gz|tar|bz2|rar|7z|mp3|mp4|flv|mov|avi|pdf)$ no-gzip dont-vary
</IfModule>
保存后重启 Apache:
sudo systemctl restart apache2
sudo nano /etc/apache2/conf-available/deflate.conf
写入相同内容,然后启用:
sudo a2enconf deflate
sudo systemctl restart apache2
curl -H "Accept-Encoding: gzip" -I http://your-domain.com
如果看到:
Content-Encoding: gzip
说明已成功开启 ✅
Content-Encoding: gzip
apache2ctl -M | grep deflate
<VirtualHost> 内✅ 不推荐
图片(jpg/png/webp)通常已压缩,再次 Gzip 反而不划算。
mod_deflate如果你希望比 Gzip 更好的压缩效果,可以安装 mod_brotli:
sudo apt install apache2 mod_brotli
sudo a2enmod brotli
sudo systemctl restart apache2
如果你愿意,可以告诉我:
我可以帮你给出更精确的配置方案 ✅