在 CentOS + Apache 上开启 Gzip(实际是 mod_deflate) 压缩,一般步骤如下:
CentOS 默认通常已包含该模块,检查是否存在:
httpd -M | grep deflate
看到 deflate_module (shared) 就说明已启用。
如果没有,安装 Apache 完整包:
yum install httpd -y
编辑 Apache 配置文件:
vi /etc/httpd/conf/httpd.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|rar|exe|flv|mp3|mp4|avi)$ no-gzip dont-vary
</IfModule>
vi /etc/httpd/conf.d/deflate.conf
内容同上。
systemctl restart httpd
或(老版本):
service httpd restart
curl -I -H "Accept-Encoding: gzip" http://localhost/
看到:
Content-Encoding: gzip
说明成功。
F12 → Network → 查看 Response Headers 中是否有:
Content-Encoding: gzip
mod_deflate 已加载conf.d 或主配置中已压缩文件(jpg/png/mp4/zip)开启 Gzip 反而浪费 CPU
如果你用的是 CentOS 8 / Stream / Apache 2.4,或需要 针对某个虚拟主机开启,可以告诉我,我可以给你精确配置。