Last Updated: February 25, 2016
·
6.123K
· robsonmwoc

Serving pre-compressed assets through Apache

Hi there!

A long time ago, I've shared with some fellows that is possible to serve compressed (gz) files directly from Apache, and save some network bandwidth with it.

I more used to Nginx, so I confess that achieve this with Apache was a little trickier.

After some tweaking over my Apache virtual host configuration, using mode deflate to serve the compressed assets I got a problem. My files seems to be compressed twice. Googling a little I found this stackoverflow answer http://stackoverflow.com/a/7510773/537235 that solve my problem.

If you're using Rails and precompile your assets, so it will minify and compress for you. Therefore you are not required to config Apache's mode deflate, because you will be serving pre-compressed content, instead of compress during the request time, which could be expensive for you server.

The following solution works fine with virtual host configuration of .htaccess. It's not usual for me put a .htaccess file inside public/assets folder in a Rails application, so, I did it using the virtual host.

<VirtualHost *:80>

    ServerName mywebsite.com

    DocumentRoot /my/rails_app/public

    <Directory /my/rails_app/public>
        AllowOverride all
        Options -MultiViews
    </Directory>

    <Location /assets/>
        RewriteEngine on

        # Make sure the browser supports gzip encoding before we send it
        # without it, Content-Type will be "application/x-gzip"

        RewriteCond %{HTTP:Accept-Encoding} \b(x-)?gzip\b
        RewriteCond %{REQUEST_FILENAME}.gz -s
        RewriteRule ^(.+) $1.gz [L]
    </Location>

    # 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 text/javascript
        Header set Content-Encoding gzip
    </FilesMatch>

</VirtualHost>

I hope this help you too.