如何让Apache启用gzip压缩?

57

我无法让我的网站使用gzip压缩。

最近我看了css-tricks.com的Chris Coyier的这个视频。在视频中,他谈到启用gzip压缩以使网站运行更快。

按照他的指示,我通过html5boilerplate.com链接到github,并从他们的.htaccess文件中复制了gzip压缩代码,然后将其粘贴到自己的文件中,最后上传到我的网站。

我已经通过gzipwtf.com进行了测试,但好像并没有起作用。有人能帮我吗?

我的.htaccess文件如下:

# ----------------------------------------------------------------------
# Trim www
# ----------------------------------------------------------------------

RewriteEngine On
RewriteCond %{HTTP_HOST} !^orbitprint.com$ [NC]
RewriteRule ^(.*)$ http://orbitprint.com/$1 [L,R=301]

# ----------------------------------------------------------------------
# Gzip compression
# ----------------------------------------------------------------------

<IfModule mod_deflate.c>

  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # Compress all output labeled with one of the following MIME-types
  <IfModule mod_filter.c>
    AddOutputFilterByType DEFLATE application/atom+xml \
                                  application/javascript \
                                  application/json \
                                  application/rss+xml \
                                  application/vnd.ms-fontobject \
                                  application/x-font-ttf \
                                  application/xhtml+xml \
                                  application/xml \
                                  font/opentype \
                                  image/svg+xml \
                                  image/x-icon \
                                  text/css \
                                  text/html \
                                  text/plain \
                                  text/x-component \
                                  text/xml
  </IfModule>

</IfModule>

1
你能添加一些关于你的服务器的细节吗?例如响应头?.htaccess只适用于Apache服务器,如果你的Apache服务器没有启用mod_filter.c,压缩就不会起作用。 - Paolo Stefan
日期:2012年9月11日,星期二,格林威治标准时间10:46:19 服务器:Apache/2.0.63(Unix)mod_ssl/2.0.63 OpenSSL/0.9.8e-fips-rhel5 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 X-Powered-By:PHP/5.2.9 过期时间:1981年11月19日,星期四,格林威治标准时间08:52:00 缓存控制:不存储、不缓存、必须重新验证、不进行后检查、不进行预检查 Pragma:无缓存 连接:关闭 传输编码:分块 内容类型:文本/ HTML - dai.hop
10个回答

93

尝试这个:

####################
# GZIP COMPRESSION #
####################
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/x-httpd-php
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip

8
这里的Vary头是什么?它是否必要? - Murat Ayfer
@MuratAyfer 这与处理代理服务器有关。我不知道具体细节。 - mwcz
7
可以为每行代码提供解释吗? - texelate
2
“Header append Vary User-Agent env=!dont-vary”这行代码看起来有些可疑。除非您向不同的用户代理提供不同的内容,否则不应该通过用户代理进行“变化”。否则,它会完全破坏您的缓存命中率。基本上,“Vary”标头所做的是允许您指示缓存将在“Vary”标头中命名的请求标头的值视为可缓存请求键的一部分,就像它是查询参数的一部分。关于此行代码的另一个讨论:https://dev59.com/AHNA5IYBdhLWcg3wa9Kp - jerryb
3
@jerryb - 这是因为他把答案从互联网上复制粘贴过来了... https://varvy.com/pagespeed/enable-compression.html - vsync

39

最好按照下面的代码片段来实现。

只需将以下内容粘贴到您的.htaccess文件中,然后使用Google PageSpeedPingdom ToolsGTmetrics检查性能。

# Enable GZIP
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</ifmodule>

# Expires Headers - 2678400s = 31 days
<ifmodule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 7200 seconds"
  ExpiresByType image/gif "access plus 2678400 seconds"
  ExpiresByType image/jpeg "access plus 2678400 seconds"
  ExpiresByType image/png "access plus 2678400 seconds"
  ExpiresByType text/css "access plus 518400 seconds"
  ExpiresByType text/javascript "access plus 2678400 seconds"
  ExpiresByType application/x-javascript "access plus 2678400 seconds"
</ifmodule>

# Cache Headers
<ifmodule mod_headers.c>
  # Cache specified files for 31 days
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  # Cache HTML files for a couple hours
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  # Cache PDFs for a day
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  # Cache Javascripts for 31 days
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</ifmodule>

我只需要将这个添加到根目录,就能让所有子文件夹都起作用吗? - Harsha M V
为什么需要同时使用 ExpiresByTypeHeader set Cache-Control - Chloe
我提供完整的.htaccess代码,以便在Google PageSpeed Insight上通过“启用压缩”和“利用浏览器缓存”。(链接:https://dev59.com/LGw15IYBdhLWcg3wA3KT#29488825) - eQ19
一个快速的评论 - 为jpg和jpeg添加类型非常重要。 - George

11
您的 .htaccess 应该可以正常运行;它依赖于四个不同的 Apache 模块(每个 <IfModule> 指令一个)。我猜测以下其中之一:
  • 您的 Apache 服务器没有安装和运行 mod_filter、mod_deflate、mod_headers 和/或 mod_setenvif 模块。如果您可以访问服务器配置,请检查 /etc/apache2/httpd.conf(以及相关的 Apache 配置文件);否则,您可以通过 phpinfo() 查看加载了哪些模块,在 apache2handler 部分下(请参见附图);(编辑)或者,您可以打开终端窗口并发出命令 sudo apachectl -M 列出已加载的模块;

  • 如果您收到 http 500 内部服务器错误,则您的服务器可能不允许使用 .htaccess 文件;

  • 您正在尝试加载一个发送自己的标题的 PHP 文件(覆盖 Apache 的标题),从而“混淆”浏览器。

无论如何,您都应该仔细检查您的服务器配置和错误日志,以了解出现了什么问题。为了确保,尝试在 Apache 文档中建议的最快方法 here 使用:

AddOutputFilterByType DEFLATE text/html text/plain text/xml

请尝试加载一个大的文本文件(最好先清除缓存)。
(编辑)如果所需的模块已经存在于Apache模块目录中,但未加载,请编辑/etc/apache2/httpd.conf并为每个模块添加LoadModule指令。
如果所需的模块既没有加载,也不在Apache模块目录中,恐怕唯一的选择是重新安装Apache(完整版本)。

phpinfo() apache2handler section


我的phpinfo()页面没有apache2handler部分,在我的httpd.conf文件中没有提到任何这些模块,而我的apache模块文件夹似乎非常稀少。这是典型的吗? - dai.hop
不,这一点也不典型。我本来期望会有更多的模块在那里……这是一个定制打包的Apache吗? - Paolo Stefan
我不确定,因为这是Pixelinternet在我购买服务器时配置的方式。我将联系我的托管公司,看看他们是否能帮助我安装所需的模块。感谢您的帮助! - dai.hop
我已经搞定了。mod_filter模块需要Apache 2.1或更高版本。由于我正在运行2.0版本,所以html5boilerplate代码永远不会对我起作用! - dai.hop

9

首先,进入apache/bin/conf/httpd.conf文件并确保mod_deflate.so已启用。

然后,进入.htaccess文件并添加以下行:

SetOutputFilter DEFLATE

这应该输出作为gzip压缩的所有内容。我已尝试过,它有效。


2
在我的情况下,我使用了以下代码来在Apache Web服务器中启用gzip压缩。
  # Compress HTML File, CSS File, JavaScript File, Text File, XML File and Fonts
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/x-httpd-php
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf

我参考了http://www.tutsway.com/enable-gzip-compression-using-htacess.php

该网站介绍了如何使用 .htaccess 文件启用 Gzip 压缩,以减少网站加载时间并提高性能。


2
使用相同的.htaccess配置遇到了这个问题。我意识到我的服务器将javascript文件作为"text/javascript"而不是"application/javascript"提供。一旦我在“AddOutputFilterByType”声明中添加了"text/javascript",gzip就开始工作了。
至于为什么javascript被提供为"text/javascript":我的根.htaccess文件顶部有一个"AddType 'text/javascript' js"声明。删除它后(这是错误添加的),javascript开始作为"application/javascript"提供。

2
如果您的Web主机是通过C Panel,则需要在Apache C Panel上启用G ZIP压缩。
进入CPanel并检查软件选项卡。
以前,优化网站功能可以使用,但现在有一个新选项可用,即“MultiPHP INI编辑器”。
选择要压缩的域名。
向下滚动到底部,直到找到zip输出压缩并启用它。
现在再次检查G ZIP压缩。
您还可以按照视频教程进行操作。 https://www.youtube.com/watch?v=o0UDmcpGlZI

1

通过 .htaccess 启用压缩

对于大多数人来说,通过在他们的 Web 主机/服务器上的名为 .htaccess 的文件中添加一些代码即可启用压缩。这意味着要前往您的 Web 主机上的文件管理器(或者您去添加或上传文件的任何地方)。

.htaccess 文件控制着您的网站的许多重要内容。

应将下面的代码添加到您的 .htaccess 文件中...

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

保存 .htaccess 文件,然后刷新您的网页。

使用 Gzip 压缩工具 检查您的压缩是否正常工作。


1
在我的情况下,只有添加这一行才有效: SetOutputFilter DEFLATE

1
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
# Insert filters
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-httpd-fastphp
AddOutputFilterByType DEFLATE image/svg+xml

# Drop problematic browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</IfModule>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接