home / blog

HTTP compression of static content with .htaccess

I was originally using mod_deflate however I had the following issues

  • Content-length was not populated which meant I couldn’t implement an AJAX progress bar
  • Weird error net::ERR_INVALID_CHUNKED_ENCODING on OS X with Chrome on transfers bigger than 1MB – I couldn’t find any other platforms effected by this.
  • Unnecessary server load

Things to note. The header content-encoding gzip is only set if the environment variable GZIP is set true. The check however is made against REDIRECT_GZIP. This is just how environment variables work within rewrite conditions – set a variable called FOO and then check against the variable with a REDIRECT_ prefix, i.e. REDIRECT_FOO.

ForceType application/json
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f 
RewriteRule ^(.+)$ $1.gz [L,E=GZIP:true]
Header set Content-Encoding gzip env=REDIRECT_GZIP
</IfModule>

Also important is the Vary: Accept-Encoding. This means that different clients going through the same proxy will behave correctly. Some might support gzip, some might not.

<IfModule mod_headers.c>
Header append Vary: Accept-Encoding
</IfModule>
This entry was posted in geek and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.