在 Ubuntu + Apache 下开启 Gzip 压缩,通常是通过 mod_deflate 模块实现的。下面给出最常见、可用的做法。
sudo a2enmod deflate
sudo systemctl restart apache2
编辑 Apache 配置文件(任选其一):
sudo nano /etc/apache2/conf-available/gzip.conf
sudo nano /etc/apache2/sites-available/000-default.conf
<IfModule mod_deflate.c>
# 压缩常见文本类型
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript application/x-javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/woff font/woff2
# 兼容老浏览器
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|exe|mp3|mp4|avi|mov)$ no-gzip
</IfModule>
保存后:
sudo systemctl restart apache2
curl -I -H "Accept-Encoding: gzip" http://localhost
看到:
Content-Encoding: gzip
说明成功。
Content-Encoding: gzip
gzencode()Ubuntu 20.04 / 22.04 默认已支持,无需额外安装。
如果你使用的是 Apache + PHP / Laravel / WordPress,或者 Docker 环境,可以告诉我,我可以给你更精确的配置。