温馨提示×

centos apache如何开启gzip

小樊
41
2026-10-11 20:07:10
栏目: 智能运维

在 CentOS + Apache 上开启 Gzip(实际是 mod_deflate) 压缩,一般步骤如下:


一、确认 Apache 已安装 mod_deflate

CentOS 默认通常已包含该模块,检查是否存在:

httpd -M | grep deflate

看到 deflate_module (shared) 就说明已启用。

如果没有,安装 Apache 完整包:

yum install httpd -y

二、开启 Gzip 配置

方法一:修改主配置文件(推荐)

编辑 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

内容同上。


三、重启 Apache

systemctl restart httpd

或(老版本):

service httpd restart

四、验证 Gzip 是否生效

方法 1:curl 测试

curl -I -H "Accept-Encoding: gzip" http://localhost/

看到:

Content-Encoding: gzip

说明成功。

方法 2:浏览器

F12 → Network → 查看 Response Headers 中是否有:

Content-Encoding: gzip

五、常见问题

1. 配置不生效

  • 确认 mod_deflate 已加载
  • 确认配置在 conf.d 或主配置中
  • 清除浏览器缓存

2. 图片/视频不要压缩

已压缩文件(jpg/png/mp4/zip)开启 Gzip 反而浪费 CPU


如果你用的是 CentOS 8 / Stream / Apache 2.4,或需要 针对某个虚拟主机开启,可以告诉我,我可以给你精确配置。

0 踩