温馨提示×

ubuntu apache怎样开启gzip

小樊
32
2026-09-17 09:21:45
栏目: 智能运维

在 Ubuntu 上通过 Apache 开启 Gzip 压缩(通常使用的是 mod_deflate 模块),可以按下面的步骤操作:


一、启用必要的 Apache 模块

Apache 使用 mod_deflate 来实现 Gzip 压缩,先确认并启用它:

sudo a2enmod deflate
sudo a2enmod headers   # 可选,但推荐

启用后重启 Apache:

sudo systemctl restart apache2

二、配置 Gzip 压缩

方法 1:修改 Apache 全局配置(推荐)

编辑 Apache 配置文件:

sudo nano /etc/apache2/mods-enabled/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/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>

保存后重启 Apache:

sudo systemctl restart apache2

方法 2:在网站虚拟主机中开启

如果你只想对某个站点开启 Gzip,可在网站配置中加:

sudo nano /etc/apache2/sites-available/your-site.conf

<VirtualHost *:80><Directory> 中加入:

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>

然后:

sudo systemctl restart apache2

三、验证 Gzip 是否生效

方法 1:使用 curl

curl -I -H "Accept-Encoding: gzip" http://your-domain.com

看到:

Content-Encoding: gzip

说明已开启。

方法 2:在线工具

  • https://www.giftofspeed.com/gzip-test/
  • https://tools.keycdn.com/gzip-test

四、常见问题

1. 修改后不生效?

  • 确认模块已启用:apache2ctl -M | grep deflate
  • 清除浏览器缓存
  • 确认无 CDN 缓存干扰

2. 图片/视频需要 Gzip 吗?

不需要,它们本身已压缩,Gzip 反而浪费 CPU。


如果你使用的是 Apache + PHP(如 WordPress)Docker 环境,我也可以给你更具体的配置。

0