在 Ubuntu 上给 Apache2 开启 gzip(实际是 mod_deflate) 压缩,一般按下面步骤来:
sudo a2enmod deflate
sudo a2enmod headers
sudo systemctl restart apache2
deflate:负责 gzip 压缩headers:可选,用于设置缓存/压缩头编辑配置文件(任选其一):
sudo nano /etc/apache2/conf-available/compress.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 font/ttf font/otf 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
# 不压缩 Already-compressed 文件
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|rar|exe|mp3|mp4|avi)$ no-gzip
</IfModule>
启用配置并重启:
sudo a2enconf compress
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/css application/javascript
</IfModule>
然后:
sudo systemctl restart apache2
curl -H "Accept-Encoding: gzip" -I http://localhost
看到:
Content-Encoding: gzip
说明成功 ✅
Content-Encoding: gzipapache2ctl -M | grep deflateAddOutputFilterByType 中如果你用的是 PHP / WordPress / Laravel,或者 Apache + Nginx,可以告诉我,我给你更具体的配置。