在 CentOS 下让 Apache 开启 Gzip 压缩,通常是通过 mod_deflate 模块实现的。下面按常见场景说明。
CentOS 默认一般已安装该模块,先检查:
httpd -M | grep deflate
如果看到:
deflate_module (shared)
说明已启用。
如果没有,可安装或启用:
yum install mod_deflate
编辑配置文件:
vi /etc/httpd/conf/httpd.conf
或在:
/etc/httpd/conf.d/
下新建一个文件,例如 gzip.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|tgz|rar|bz2|mp3|mp4|avi|mov)$ no-gzip dont-vary
</IfModule>
如果你使用的是虚拟主机:
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/html
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
</VirtualHost>
systemctl restart httpd
或(老版本):
service httpd restart
curl -I -H "Accept-Encoding: gzip" http://localhost/
看到:
Content-Encoding: gzip
说明成功。
F12 → Network → 查看响应头:
Content-Encoding: gzip
mod_deflate 已加载mod_deflatemod_gzip 较老,不推荐如果你用的是 CentOS 版本(6/7/8) 或 Apache 2.2 / 2.4,可以告诉我,我可以给你更精确的配置。