Skip to content

Enable Compression in Apache

Chirag Sanghvi edited this page Oct 4, 2016 · 10 revisions

Installation

Module Mod_deflate is included and enabled in the default Apache installation on CentOS 7. To confirm this run apachectl, the Apache Server Control Interface, and filter the output with grep for the keyword deflate like this:

$ apachectl -t -D DUMP_MODULES | grep deflate

You should see deflate_module (shared) if mod_deflate is installed and enabled. If you don't see this, follow these troubleshooting steps:

  1. Ensure that the module file is installed. This file is part of the core httpd package which you should already have installed per the previously mentioned prerequisites. By default, it is found in /etc/httpd/modules/mod_deflate.so. Also, the web server should be able to open this file. For this purpose mod_deflate.so should have world readable permissions such as 755.
  2. Check if the module has been loaded. Open the Apache base modules configuration file /etc/httpd/conf.modules.d/00-base.conf and ensure this line is present and not commented out:
LoadModule deflate_module modules/mod_deflate.so

Configuration

To start using mod_deflate you have to specify which file types should be compressed. On one hand, plain text formats can be greatly reduced in size by compression, and that's why it makes sense to apply it to HTML, CSS, or JavaScript files. On the other hand, many multimedia formats such as Flash and pictures already have compression in them, and additional compression will be futile.

To configure mod_deflate, create a new configuration file /etc/httpd/conf.d/mod_deflate.conf with the sample code:

<IfModule mod_deflate.c>

  # place filter 'DEFLATE' on all outgoing content
  SetOutputFilter DEFLATE

  # exclude uncompressible content via file type
  SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|rar|zip)$ no-gzip

  # Force proxies to cache compressed & non-compressed files separately.
  <IfModule mod_headers.c>
    # properly handle requests coming from behind proxies
    Header append Vary User-Agent
  </IfModule>

</IfModule>

The above code means that compress files whose extensions are not gif|jpe?g|png|rar|zip (images, zip and rar files) through the standard Apache SetOutputFilter Deflate directive.

NOTE: Don't forget to restart Apache if you have had to make a change in the Apache configuration. The restart command is sudo apachectl restart.

Clone this wiki locally