在 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
添加或修改内容:
<IfModule mod_deflate.c>
# 压缩常见文本类型
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-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|tar|bz2|mp3|mp4|webm)$ no-gzip dont-vary
</IfModule>
启用配置并重启:
sudo a2enconf deflate
sudo systemctl restart apache2
编辑你的站点配置:
sudo nano /etc/apache2/sites-available/your-site.conf
在 <VirtualHost *:80> 或 <Directory> 中添加:
<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
重启 Apache:
sudo systemctl restart apache2
curl -I -H "Accept-Encoding: gzip" http://your-domain.com
如果看到:
Content-Encoding: gzip
说明成功。
Content-Encoding: gzip
apache2ctl -M | grep deflate如果你愿意,可以告诉我:
我可以给你更精确的配置。