【问题标题】:Prevent apache from changing content type when rewriting防止apache在重写时改变内容类型
【发布时间】:2016-06-17 16:48:23
【问题描述】:

我有一个静态网页,想通过提供所有可用文件的 gzip 版本来提高加载性能。该页面在 apache 服务器 mod_gzip 上运行,除了 .htaccess 文件之外,我无法更改任何配置。 因此,我在构建过程中创建了 gzip 文件,并希望将传入的请求重写为 .gz 文件。

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    ReWriteCond %{HTTP:accept-encoding} gzip
    ReWriteCond %{REQUEST_FILENAME} !.+\.gz$
    RewriteCond %{REQUEST_FILENAME}.gz -f
    RewriteRule (.+) $1.gz [L]
</IfModule>

重写工作完美,但不幸的是服务器也将响应的 Content-Type 更改为 application/x-gzip 这使得浏览器下载文件而不是渲染它。有没有办法阻止 apache 服务器更改内容类型并呈现页面而不是下载 gz?

【问题讨论】:

  • 您有哪些文件的 gz 版本? html、css、js?
  • 是的,html、css 和 js。还有字体文件(eot、ttf、woff...)

标签: apache .htaccess mod-rewrite gzip content-type


【解决方案1】:

这要求您拥有以下格式的文件的 2 个版本。例如:

index.html
index.html.gz

styles.css
styles.css.gz

scripts.js
scripts.js.gz

此 htaccess 将重写请求以将 gz 版本发送到浏览器,但也会保持原始文件的类型。您必须强制您要发送的文件的类型。否则它将使用application/x-gzip 并且浏览器将下载文件。

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json application/javascript application/vnd.ms-fontobject application/font-ttf application/font-woff application/font-otf image/svg+xml
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP:Accept-Encoding} gzip
    RewriteCond %{REQUEST_FILENAME}.gz -f
    RewriteRule (.*\.(html|css|js|eot|ttf|woff|otf|svg))$ $1.gz [L]
</IfModule>

AddEncoding x-gzip .gz

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

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

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

<FilesMatch .*\.eot.gz>
    ForceType application/vnd.ms-fontobject
</FilesMatch>

<FilesMatch .*\.ttf.gz>
    ForceType application/font-ttf
</FilesMatch>

<FilesMatch .*\.woff.gz>
    ForceType application/font-woff
</FilesMatch>

<FilesMatch .*\.otf.gz>
    ForceType application/font-otf
</FilesMatch>

<FilesMatch .*\.svg.gz>
    ForceType image/svg+xml
</FilesMatch>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2013-11-27
    • 2014-04-02
    • 1970-01-01
    相关资源
    最近更新 更多