【问题标题】:How to serve compressed/uncompressed files based on request's accepted encoding types by having only compressed files如何仅通过压缩文件根据请求接受的编码类型提供压缩/未压缩文件
【发布时间】:2014-05-24 06:50:09
【问题描述】:

在 apache htdocs 中,我只想拥有压缩文件(gzip 文件)并根据请求接受的编码类型,如果启用 gzip 编码,我希望 apache 提供压缩文件,如果不支持 gzip 编码,那么我希望 apache 通过解压缩 gzip 文件来提供服务。

我不想保留未压缩的文件并在访问时使用 deflate 进行压缩,因为这将是低效的,并且默认情况下所有客户端都支持 gzip 编码。

通过同时拥有压缩和未压缩文件(example.js 和 example.jsgz 都在 htdocs 目录中),我能够通过使用 RedirectCond on request 接受的编码和 RedirectRules 来完成这项工作。但这需要存储两个文件(压缩文件和普通文件)。以下是我与重定向规则一起使用的配置。

<Directory /var/www/app>
AddEncoding gzip .jsgz .cssgz .htmlgz
AddType text/javascript .jsgz
AddType text/css .cssgz
AddType text/html .htmlgz
SetEnv force-no-vary
Header set Cache-Control "private"

RewriteEngine on
# If client accepts compressed files
RewriteCond %{HTTP:Accept-Encoding} gzip
# and if compressed file exists
RewriteCond %{REQUEST_FILENAME}gz -f
# send .htmlgz instead of .html
RewriteRule ^(.+)\.(html|css|js)$ $1.$2gz [L]
</Directory>

我不想像上面那样做,因为我必须保留每个文件的两个版本。

例如:

htdocs 中 app 目录的内容

ls app/
example.jsgz

app 目录的服务器端 apache 配置

在这种情况下,使用 MultiView 选项,当请求文件为 example.js 时,我可以服务器 example.jsgz,因为 example.js 不存在。我的 apache 端的配置如下:

<Directory /var/www/htdocs/app>
AddEncoding gzip .jsgz .cssgz .htmlgz
AddType text/javascript .jsgz
AddType text/css .cssgz
AddType text/html .htmlgz
Options +Multiviews
SetEnv force-no-vary
Header set Cache-Control "private"
</Directory>

案例一:

请求标头说支持 gzip 编码。并且请求的 url 是 example.js 而不是 example.jsgz。这是有效的,example.jsgz 文件以 gzip 的内容编码提供,客户端能够解压缩并使用 js 文件。

Request URL:http://A.B.C.D/app/example.js
Request Method:GET
Request HTTP headers: 
Accept-Encoding:gzip,deflate,sdch

Response Headers:
Content-Encoding:gzip

案例 2:

请求标头显示不支持 gzip 编码。并且请求的 url 是 example.js 而不是 example.jsgz。这不起作用,因为 apache 正在服务 example.jsgz 并且客户端失败,因为不支持 gzip 编码。

Request URL:http://A.B.C.D/app/example.js
Request Method:GET
Request HTTP headers: 

Response Headers:
Content-Encoding:gzip

当客户端不支持 gzip 编码时,是否有办法通过仅在 htdocs 中包含压缩文件来处理案例 2?

我已阅读有关充气和放气选项的信息。还有关于多视图选项。但是当目录包含压缩格式(gzip 编码)的多种类型的内容(javascript、css、html)时,我没有在目录级别找到示例。

提前致谢

【问题讨论】:

    标签: apache


    【解决方案1】:

    看起来这就是你需要的http://www.innerjoin.org/apache-compression/howto.html

    虽然我没有以任何方式尝试过。

    另一种选择可能是使用一些脚本语言来运行解压和响应(php、ruby、perl...)

    就性能而言,同时拥有两个版本是最好的选择,因为它不需要任何额外的努力。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多