【问题标题】:How to configure mod_deflate to serve gzipped assets prepared with assets:precompile如何配置 mod_deflate 以提供使用 assets:precompile 准备的 gzipped 资产
【发布时间】:2011-09-22 04:16:15
【问题描述】:

运行 assets:precompile rake 任务时,会创建应用资产的 gzip 版本。根据资产管道的 Rails 指南,您可以配置您的 Web 服务器(在我的情况下为 Apache 2.2)来提供这些预压缩文件,而不是让 Web 服务器完成这项工作。

我想不通的是如何配置 mod_deflate 以便提供这些文件而不是双重压缩然后提供?

我通过 httpd.conf 启用了 mod_deflate:

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

我已将 rails 指南上的代码转换为 public/assets 中的 .htaccess:

# Some browsers still send conditional-GET requests if there's a
# Last-Modified header or an ETag header even if they haven't
# reached the expiry date sent in the Expires header.

Header unset Last-Modified
Header unset ETag
FileETag None

# RFC says only cache for 1 year

ExpiresActive On
ExpiresDefault "access plus 1 year"

# Serve gzipped versions instead of requiring Apache to do the work

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.gz -s
RewriteRule ^(.+) $1.gz [L]

# without it, Content-Type will be "application/x-gzip"

<FilesMatch .*\.css.gz>
    ForceType text/css
</FilesMatch>

<FilesMatch .*\.js.gz>
    ForceType text/javascript
</FilesMatch>

任何想法如何正确设置?

【问题讨论】:

    标签: apache ruby-on-rails-3.1 asset-pipeline mod-deflate


    【解决方案1】:

    首先,您不希望 mod_deflate 在这里运行。所以在你的资产 .htaccess 文件中添加:

    SetEnv no-gzip
    

    这应该会为您的资产关闭 mod_deflate。

    其次,我讨厌不同意 Rails 的人,但我认为他们的资产 .htaccess 配方存在一些缺陷。顶部很好,但对于 RewriteEngine 及其他部分,我会有:

    RewriteEngine on
    # Make sure the browser supports gzip encoding before we send it
    RewriteCond %{HTTP:Accept-Encoding} \b(x-)?gzip\b
    RewriteCond %{REQUEST_URI} .*\.(css|js)
    RewriteCond %{REQUEST_FILENAME}.gz -s
    RewriteRule ^(.+) $1.gz [L]
    
    # without it, Content-Type will be "application/x-gzip"
    # also add a content-encoding header to tell the browser to decompress
    
    <FilesMatch \.css\.gz$>
        ForceType text/css
        Header set Content-Encoding gzip
    </FilesMatch>
    
    <FilesMatch \.js\.gz$>
        ForceType application/javascript
        Header set Content-Encoding gzip
    </FilesMatch>
    

    【讨论】:

    • 小注释 - 如果它不在 .htaccess 中,它需要在目录部分,否则 -s 将不起作用。
    • 另外,您可能应该推荐使用application/javascript 而不是text/javascript。请参阅 脚本媒体类型 上的RFC4329
    • 我必须做 AddEncoding gzip .gz 否则很好
    • Sprockets > 3.4 现在将资产编译为 .gz 文件。使用 sprockets > 3.4 时在 .htaccess 文件中包含此代码将阻止浏览器读取已编译的 css 和 js,因此无需使用此解决方案。
    猜你喜欢
    • 2011-08-04
    • 2012-06-08
    • 2015-06-12
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    相关资源
    最近更新 更多