Setting apache deflate for pre-compressed file

I could not think of a better title than this. I will explain it here.

Use-case is something like this - You want to serve your file using apache (2.x) in a compressed format using the deflate module. But you don't want apache to waste time by compressing the file on the fly. You rather want it to pick a pre-compressed file from the disk and serve it straightaway.

Sounds quite simple. Just enable the apache deflate module and edit the conf file -
sudo a2enmod deflate

This will enable the straightforward compression i.e. once enabled with this, apache will send all the files out in a compressed format, unless you edit the deflate.conf file to prevent the compression of some specific files.

Here is a snapshot of my deflate.conf-
          SetOutputFilter DEFLATE
          SetInputFilter DEFLATE
          DeflateCompressionLevel 9
          # Don't compress images
          SetEnvIfNoCase Request_URI \
          \.(?:gif|jpe?g|png|gz)$ no-gzip dont-vary
          DeflateFilterNote Input input_info
          DeflateFilterNote Output output_info
          DeflateFilterNote Ratio ratio_info
          LogFormat '"%r" %{output_info}n/%{input_info}n (%{ratio_info}n%%)' deflate
          CustomLog /var/log/apache2/deflate_log deflate


Doing this alone sets up apache for compressed serving but not for picking up a pre-compressed file from the disk. To enable it to save some time by picking the compressed file from disk, few more changes are required.

Adding MultiViews option along with the encoding mechanism does the trick. These options are added in the conf file of enabled sites -  /etc/apache2/sites-enabled/sitefoo.

Snapshot - 
                ServerAlias server
                ServerAdmin admin@localhost
                DocumentRoot /home/user/apacheroot/
               
user/apacheroot/>
                Order deny,allow
                Allow from all
                options MultiViews
                AddEncoding x-gzip .gz   

          
Once these options are enabled and apache server has been restarted, requests coming from client are handled somewhat like this -
1.Client requests for file "/foo/foo.sh"
2.Apache looks for "/foo/foo.sh". If the file "foo.sh" is not found, apache looks for other file-extensions on same filename in the same directory, like "/foo/foo.*".In this case if "/foo/foo.gz" is present, apache serves this file.
3.The AddEncoding attribute notifies the client the which encoding mechanism has been used for what file extension. Like in the above snapshot "z-gzip .gz" means that for "*.gz" files. gzip has been used. So the client is able to decompress the files and use them in their original form.

This saves significant amount of time, as apache does not have to do compression anymore.




EDIT: Enabling the deflate module is not necessary. I realized it later that once multiviews is enabled, deflate is not required at all.

0 comments:

Post a Comment