如何通过.htaccess启用Gzip或Deflate压缩?

如何通过.htaccess启用Gzip或Deflate压缩,以及哪一个最好? 代码示例需要。

    HTML5 Boilerplate( http://html5boilerplate.com )提供了似乎是最好和最有效的解决scheme设置,以及其他诸如caching,MIMEtypes等等。强烈推荐。

    <IfModule mod_deflate.c> # Force compression for mangled headers. # http://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 # (for Apache versions below 2.3.7, you don't need to enable `mod_filter` # and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines # as `AddOutputFilterByType` is still in the core directives). <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/x-web-app-manifest+json \ 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> 

    编辑:由于这个问题和答案不断得到upvoted几年后,我把H5BP服务器configuration链接进行更完整的优化 。

    编辑:修复链接到https://github.com/h5bp/server-configs-apache

    请参阅Apache mod_deflate文档,特别是“ 压缩除图像以外的所有内容 ”示例。 它对我来说工作得很好,可以放在.htaccess文件中,如下所示:

     <IfModule mod_deflate.c> # Insert filter SetOutputFilter DEFLATE # Netscape 4.x has some problems... BrowserMatch ^Mozilla/4 gzip-only-text/html # Netscape 4.06-4.08 have some more problems BrowserMatch ^Mozilla/4\.0[678] no-gzip # MSIE masquerades as Netscape, but it is fine # BrowserMatch \bMSIE !no-gzip !gzip-only-text/html # NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48 # the above regex won't work. You can use the following # workaround to get the desired effect: BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html # Don't compress images SetEnvIfNoCase Request_URI \ \.(?:gif|jpe?g|png)$ no-gzip dont-vary # Make sure proxies don't deliver the wrong content Header append Vary User-Agent env=!dont-vary </IfModule> 

    当然,请确保在httpd.conf文件中有以下内容来启用mod_deflate

     LoadModule deflate_module libexec/apache2/mod_deflate.so 

    我在我的网站(通过MIMEtypes)使用以下添加到我的public_html目录的根目录下的.htaccess文件的静态资产启用deflate:

     <ifModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/xml text/css text/plain AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript application/json </ifModule> 

    你也可以通过文件扩展来启用它,但是我没有这个方便的语法。