mod_xsendfile is a small Apache2 module which processes X-SENDFILE headers that output handlers might have registered. If the module encounters the presence of such a header it will discard all output and send the file specified by that header instead using Apache internals, specifically all optimizations like caching-headers and sendfile or mmap, if configured.

X-SENDFILE is useful because some applications require checking for special privileges, some have to look up values first, such as from a database, in order to correctly process a download request, and others store values like download counters.

So let's get started!

  1. Download and compile the xsendfile module:
$ wget
$ apxs -cia mod_xsendfile.csudo service apache2 restart
  1. Configure Apache for X-SendFile
    In /etc/apache2/apache2.conf or a configuration file in the sites-availabledirectory, depending upon virtual hosting configuration, append the following within the host directive:
XSendFile On
XSendFilePath /full/path/to/files/to/be/served/

RewriteEngine On
RewriteCond %{THE_REQUEST} ^[\S]+\ /protect/
RewriteRule ^/protect/ - [F]

Alias /protect/ /path/to/protect/
<Directory /path/to/protect/>
    Order deny,allow
    Allow from all

And that's it! If you're using mod_xsendfile with Django, I highly recommend the Django Sendfile module.