4

我想将我的网络服务器的所有静态文件保存在本地压缩,并根据请求为它们提供压缩或不压缩。

如何在 Apache 2.x 中使用 mod_deflate 预压缩文件foo.tar.gz, 很接近,因为确实通过启用 MultiViews 并使用正确的 AddEncoding,我可以让 Apache在我请求时从我的网络服务器返回压缩文件foo.tar,并且它带有正确的Content-Encoding:标题。

但这仅在客户端包含Accept-Encoding: gzip在它发送到服务器的标头中时才有效。OTOH,如果客户端不支持 gzip 编码,我的服务器只会告诉我foo.tar对我来说没有“可接受的”。

如果我使用AddOutputFilter INFLATE tar. 但是如果我这样做,那么服务器也会在我请求时foo.tar.gz(或者当我指定我接受 gzip 编码时)解压缩内容,这显然是我不想要的。

那么,当客户端不支持 gzip 内容编码但在其他情况下提供预压缩文件时,如何让 Apache 解压缩文件?

编辑:根据@covener 的建议,我尝试了以下方法:

AddEncoding x-gzip .gz .tgz
RemoveType application/x-gzip .gz .tgz
AddType application/x-tar .tgz

<Location /packages>
  FilterDeclare smgunzip CONTENT_SET
  FilterProvider smgunzip INFLATE req=Accept-Encoding !$gzip
  FilterChain smgunzip
</Location>

[ 在这里使用 Apache-2.2.22。] 但结果实际上比仅使用前三行更糟糕:当我请求 .tar.gz 文件时,它现在返回时没有“Content-Encoding:”,当我请求 .tar 文件时,我收到tar.gz 的内容(即仍然压缩),无论“Accept-Encoding:”标头如何,并且仍然没有“Content-Encoding:”。

4

2 回答 2

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>
于 2014-11-26T13:44:42.433 回答
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>

抄自 Daniel Collins,使用 Apache 提供静态 gzip 压缩内容

于 2021-02-18T12:59:56.993 回答