在 Ubuntu 上使用 Apache2 开启 Gzip(mod_deflate) 通常步骤如下:
Apache 通过 mod_deflate 实现 Gzip 压缩。
sudo a2enmod deflate
sudo a2enmod headers # 可选,但推荐
然后重启 Apache:
sudo systemctl restart apache2
编辑配置文件(二选一):
sudo nano /etc/apache2/conf-available/deflate.conf
或新建一个配置:
sudo nano /etc/apache2/conf-available/gzip.conf
写入以下内容:
<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
# 不压缩已压缩格式
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|zip|gz|tar|rar|mp3|mp4|avi|mov)$ no-gzip dont-vary
# 浏览器兼容
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</IfModule>
启用配置(如果是新建文件):
sudo a2enconf gzip
sudo systemctl restart apache2
编辑你的站点配置:
sudo nano /etc/apache2/sites-available/000-default.conf
在 <VirtualHost *:80> 内添加:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
重启 Apache:
sudo systemctl restart apache2
curl -I -H "Accept-Encoding: gzip" http://你的域名/
看到:
Content-Encoding: gzip
说明成功。
如果 Apache 前面有 Nginx 或 CDN,Gzip 可能由它们处理。
mod_deflate 对 HTTP / HTTPS 都生效。
已压缩文件(jpg、mp4、zip)开启 Gzip 反而浪费 CPU。
如果你愿意,我可以根据你的 Ubuntu 版本(20.04 / 22.04 / 24.04)或 Apache 配置结构,给你一份更精确的配置。