Vhosts: X-Sendfile

This document describes how to use mod_xsendfile on CAE vhosts to serve files more efficiently.


Normally, when an application (eg: PHP or CGI) wants to send a file (eg: PDF, image, video, etc.) that must be protected by some application code (eg: authorization checks), it needs to run the application code (eg: authorization checks), read the file into memory, then output it again. These last two steps then get repeated when passing the output through the webserver (eg: Apache) before sending it onto the network to be delivered to the client.

Additionally, it becomes the application code's responsibility to check any cache related client request headers (eg: If-Modified-Since, etc.) against the file's timestamps on the filesystem.

Each of these things is something the native webserver code (eg: Apache), does very well on it's own.

Apache's mod_xsendfile was designed to allow an application to instead return only an X-Sendfile: /absolute/path/to/file/to/serve header, in order to instruct Apache to handle of the details of serving a file efficiently to the client after the application code has made it's authorization checks.

How to use mod_xsendfile

  1. Enable the xsendfile module in the Vhost Control Panel for your site (eg: example.engr.wisc.edu):
  2. Add an XSendFile On .htaccess rule for your application code. For instance, if your application code that serves files is accessible at https://example.engr.wisc.edu/download/, then you would place the following line in /home/vhosts/example.engr.wisc.edu/html/download/.htaccess:
    XSendFile On
  3. Update your application code to send X-SendFile headers instead. For instance, if /home/vhosts/example.engr.wisc.edu/html/download/index.php contained the code to serve files requested, then your code might look something like this:
        // some code to determine the user session
        if (user_is_authorized($requested_file)) {
            header('Content-Type: '.mime_content_type($requested_file));
            header('X-Sendfile: '.realpath($requested_file));
        else {
            header('HTTP/1.0 403 Forbidden', true, 403);
            print '<h1>Unauthorized</h1>';

See Also


Keywords:mod_xsendfile sendfile xsendfile x-sendfile php cgi apache   Doc ID:36606
Owner:Jeff B.Group:Computer-Aided Engineering
Created:2014-01-21 16:29 CDTUpdated:2017-06-22 04:52 CDT
Sites:Computer-Aided Engineering
Feedback:  0   0