温馨提示×

ubuntu apache2怎么开启gzip

小樊
36
2026-09-17 08:06:42
栏目: 智能运维

在 Ubuntu 上通过 Apache2 开启 Gzip(实际常用的是 mod_deflate)步骤如下:


一、启用必要模块

Apache 通常使用 mod_deflate 来做 Gzip 压缩:

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

启用后重启 Apache:

sudo systemctl restart apache2

二、配置 Gzip(推荐方式)

方法 1:修改 Apache 配置文件(全局生效)

编辑配置文件(任选其一):

sudo nano /etc/apache2/conf-available/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/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|tar|bz2|mp3|mp4|webm)$ no-gzip dont-vary
</IfModule>

启用配置并重启:

sudo a2enconf deflate
sudo systemctl restart apache2

方法 2:在虚拟主机中开启(推荐用于站点级)

编辑你的站点配置:

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

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

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

重启 Apache:

sudo systemctl restart apache2

三、验证 Gzip 是否生效

方法 1:curl 命令

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

如果看到:

Content-Encoding: gzip

说明成功。

方法 2:浏览器

  • 打开 F12 → Network
  • 查看响应头是否有:
Content-Encoding: gzip

四、常见问题

1. 修改后不生效?

  • 确认模块已启用:apache2ctl -M | grep deflate
  • 清除浏览器缓存
  • 确认没有被 CDN 或 Nginx 覆盖

2. 图片/视频要不要压缩?

  • 不需要(jpg/png/mp4 本身已压缩)
  • 压缩反而浪费 CPU

如果你愿意,可以告诉我:

  • Ubuntu 版本
  • Apache 版本
  • 是否用了虚拟主机 / Docker / 宝塔

我可以给你更精确的配置。

0