如何通过 .htaccess 启用 Gzip 或 Deflate 压缩,目前哪一个最好?需要代码示例。
答案1
HTML5 样板 (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 服务器配置链接放在更完整的优化。
答案2
查看 Apachemod_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
答案3
.htaccess
我使用添加到目录根目录中的文件中以下内容来启用我网站上静态资产的 deflate(按 MIME 类型)public_html
:
<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>
您也可以通过文件扩展名来启用它,尽管我没有方便的语法。