javascriptapache.htaccessmod-rewritehttp-compression

How to host static content pre-compressed in apache?


I host a JavaScript game which basically consists of an .html and a .data file. If I compress them with gzip, their size shrinks to 25%. So I want to do that.

I'm not 100% sure, but I think using mod_gzip or mod_deflate does the compression on-the-fly, wasting cpu time all the time because the Content doesn't Change.

So I'ld like to precompile the Content. Therefore, I put a .gz next to the uncompressed files and put rewrite rules in .htaccess:

RewriteEngine on 
# If client accepts compressed files 
RewriteCond %{HTTP:Accept-Encoding} gzip 
# and if compressed file exists 
RewriteCond %{REQUEST_FILENAME}.gz -f 
# send .html.gz instead of .html 
RewriteRule ^(.+)\.(html|css|js|data)$ $1.$2.gz [T=text/$2,E=GZIP:gzip,L] 
Header set Content-Encoding gzip env=GZIP 

The Redirect is working, I can request game.html and actually get deliviered game.html.gz. However, the browser doesn't just display it. Instead, it asks me where to save the file. How can I fix that? Or maybe there is another way to achieve my Goal?


Solution

  • This is how i fixed once the same problem.

    Add new types in .htaccess:

    AddEncoding gzip .jsgz .cssgz .htmlgz .datagz
    AddType application/javascript .jsgz
    AddType text/css .cssgz
    AddType text/html .htmlgz       
    AddType text/plain .datagz
    

    This was done this way because AddType instruction didn't accept extensions in the form .html.gz.

    Then modify your rewrite rule:

    RewriteRule ^(.+)\.(html|css|js|data)$ $1.$2gz [L] 
    

    And finally rename your files. Remove dots from .html.gz, .js.gz and so on.

    The full .htaccess would look like this:

    AddEncoding gzip .jsgz .cssgz .htmlgz .datagz
    AddType application/x-javascript .jsgz
    AddType text/css .cssgz
    AddType text/html .htmlgz       
    AddType text/plain .datagz
    
    RewriteEngine on 
    # If client accepts compressed files 
    RewriteCond %{HTTP:Accept-Encoding} gzip 
    # and if compressed file exists 
    RewriteCond %{REQUEST_FILENAME}gz -f 
    # send .html.gz instead of .html 
    RewriteRule ^(.+)\.(html|css|js|data)$ $1.$2gz [L]