Code: Content Negotiation in Apache

Chapter 9 - Advanced Web Performance Optimization

Since version 1.3.4, Apache has supported transparent content negotiation as defined in the HTTP 1.1 specification. To negotiate a resource, the server needs to know about the variants of each resource. Multiviews implicitly maps variants based on filename extensions, such as .gz. Multiviews is a per-directory option that you can set within files or within server configuration files (such as httpd.conf) on one or more directories. Setting the Multiviews option within the .conf file is more efficient because Apache doesn't have to access an .htaccess file every time it accesses a directory. To turn on Multiviews, append it to the Options line in your httpd.conf file:

<Directory "/usr/local/apache/htdocs">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

Apache recognizes only encodings that are defined by the AddEncoding directive. So, to let Apache know about gzip-encoded files, you'd add the following directive:

# AddEncoding allows you to have certain browsers
# uncompress information on the fly. Note: Not all browsers
# support this. Despite the name similarity, the following
# Add* directives have nothing to do with the FancyIndexing
# customization directives above.
#
AddEncoding x-gzip .gz .tgz

Now, with Multiviews set, webmasters need only create filename variants of resources, and Apache does the rest. So, to create gzip-compressed versions of your .html or .js files, you zip them up like this:

gzip -9 index.html
gzip -9 script.js

Then, when you link to the uncompressed .html or .js files, Apache will negotiate to the .gz variant for capable browsers.

Content negotiation can produce significant overhead, on the order of 25% in some cases. But as long as your server's response time is measured in milliseconds, your users won't notice the difference in response times. The net effect will be faster because smaller files are being transferred and decompression times are fast.