我想保持我的网络服务器的所有静态文件在本地压缩,并根据请求压缩或不压缩它们。
How can I pre-compress files with mod_deflate in Apache 2.x?中的答案很接近,因为实际上通过启用MultiView并使用正确的AddEncoding,我可以让Apache在我请求时从我的web服务器返回压缩的foo.tar.gz
文件{ {1}},它带有正确的foo.tar
标题。
但这仅在客户端在其发送到服务器的标头中包含Content-Encoding:
时才有效。 OTOH如果客户端不支持gzip编码,我的服务器告诉我,对我来说没有“可接受的”Accept-Encoding: gzip
。
如果我使用foo.tar
,我可以让Apache在发送之前解压缩该tarball。但是,如果我这样做,那么当我请求AddOutputFilter INFLATE tar
时(或当我指定我接受gzip编码时),服务器也会解压缩内容,这显然是我不想要的。
那么当客户端不支持gzip内容编码时如何让Apache解压缩文件,而在其他情况下如何提供预压缩文件呢?
编辑:基于@covener的建议,我尝试了以下内容:foo.tar.gz
[在这里使用Apache-2.2.22。 ]但结果实际上比前三行更糟糕:当我请求.tar.gz文件时,它现在返回而没有“Content-Encoding:”,当我请求.tar文件时,我收到了tar.gz的内容(即仍然是压缩的),无论“Accept-Encoding:”标头如何,仍然没有“Content-Encoding:”。
答案 0 :(得分:6)
(确保您有AddEncoding gzip或x-gzip gz或它会破坏)
2.4:
<Directory /home/covener/SRC/2.4.x/built/htdocs>
Options +MultiViews
MultiviewsMatch Any
FilterDeclare gzip CONTENT_SET
FilterProvider gzip INFLATE "! req('Accept-Encoding') =~ /gzip/"
FilterChain gzip
</Directory>
2.2:
<Directory /home/covener/SRC/2.2.x/built/htdocs>
Options +MultiViews
MultiviewsMatch Any
FilterDeclare gzip CONTENT_SET
FilterProvider gzip INFLATE req=Accept-Encoding !$gzip
FilterChain gzip
</Directory>
答案 1 :(得分:0)
试试这个:
DirectoryIndex "index.html.gz" "index.html"
# Don't list the compressed files in directory indexes - you probably don't want to expose
# the .gz URLs to the outside. They're also misleading, since requesting them will give the
# original files rather than compressed ones.
IndexIgnore "*.html.gz" "*.css.gz"
RewriteEngine On
# Rewrite requests for .html/.css files to their .gz counterparts, if they exist.
RewriteCond "%{DOCUMENT_ROOT}%{REQUEST_FILENAME}.gz" -s
RewriteRule "^(.*)\.(html|css)$" "$1\.$2\.gz" [QSA]
# Serve compressed HTML/CSS with the correct Content-Type header.
RewriteRule "\.html\.gz$" "-" [T=text/html,E=no-gzip:1]
RewriteRule "\.css\.gz$" "-" [T=text/css,E=no-gzip:1]
# Define a filter which decompresses the content using zcat.
# CAVEAT: This will fork a new process for every request made by a client that doesn't
# support gzip compression (most browsers do), so may not be suitable if you're running a
# very busy site.
ExtFilterDefine zcat cmd="/bin/zcat -"
<FilesMatch "\.(html|css)\.gz$">
<If "%{HTTP:Accept-Encoding} =~ /gzip/">
# Client supports gzip compression - pass it through.
Header append Content-Encoding gzip
</If>
<Else>
# Client doesn't support gzip compression - decompress it.
SetOutputFilter zcat
</Else>
# Force proxies to cache gzipped & non-gzipped css/js files separately.
Header append Vary Accept-Encoding
</FilesMatch>
摘自丹尼尔柯林斯,Serving static gzip-compressed content with Apache。