在 Ubuntu 上通过 Apache 开启 Gzip 压缩(通常使用的是 mod_deflate 模块),可以按下面的步骤操作:
Apache 使用 mod_deflate 来实现 Gzip 压缩,先确认并启用它:
sudo a2enmod deflate
sudo a2enmod headers # 可选,但推荐
启用后重启 Apache:
sudo systemctl restart apache2
编辑 Apache 配置文件:
sudo nano /etc/apache2/mods-enabled/deflate.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 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|tgz|rar|bz2|mp3|mp4|avi|mov)$ no-gzip dont-vary
</IfModule>
保存后重启 Apache:
sudo systemctl restart apache2
如果你只想对某个站点开启 Gzip,可在网站配置中加:
sudo nano /etc/apache2/sites-available/your-site.conf
在 <VirtualHost *:80> 或 <Directory> 中加入:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
然后:
sudo systemctl restart apache2
curl -I -H "Accept-Encoding: gzip" http://your-domain.com
看到:
Content-Encoding: gzip
说明已开启。
apache2ctl -M | grep deflate不需要,它们本身已压缩,Gzip 反而浪费 CPU。
如果你使用的是 Apache + PHP(如 WordPress) 或 Docker 环境,我也可以给你更具体的配置。