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!
- Download and compile the
xsendfile
module:
$ wget https://github.com/sdaylor/mod_xsendfile/blob/master/mod_xsendfile.c
$ apxs -cia mod_xsendfile.csudo service apache2 restart
- Configure Apache for X-SendFile
In/etc/apache2/apache2.conf
or a configuration file in thesites-available
directory, 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
</Directory>
And that's it! If you're using mod_xsendfile
with Django, I highly recommend the Django Sendfile module.