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


Answers:


15

HTML5 Boilerplate(http://html5boilerplate.com)提供了似乎是最好,最有效的解决方案设置,以及诸如缓存,mime类型等许多其他设置。强烈建议使用。

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

编辑:由于这个问题和答案在几年后一直受到反对,我将H5BP服务器配置链接用于更全面的优化

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


12

请参阅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

9

.htaccesspublic_html目录的根目录下的文件中添加了以下内容,从而对站点上的静态资产(按MIME类型)启用了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>

您也可以通过文件扩展名启用它,尽管我没有方便的语法。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.