A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Apache mod_xsendfile for my Django app (UPDATED)

Here is how to setup/install mod_xsendfile in Apache2 + Django (mod_wsgi).

First do this to install apxs2

$> sudo apt-get install apache2-prefork-dev

Download mod_xsendfile: http://tn123.ath.cx/mod_xsendfile/

Install it by doing this:

$> apxs2 -cia mod_xsendfile.c

If you get an error compiling mod_xsendfile just ignore it, see: ubuntu forums

After installing…

$> cd /etc/apache2/mods-available
$> sudo vi xsendfile.load

Put this inside the “xsendfile.load”

LoadModule xsendfile_module /usr/lib/apache2/modules/mod_xsendfile.so

Save and exit Vi.

Open your httpd conf file or the equivalent and add “XSendFile On” and “XSendFilePath /home/path/”. See example:

<VirtualHost x.x.x.x:80>
     ServerAdmin wenbert@test.com
     ServerName client.test.com
     ServerAlias www.client.test.com
     DocumentRoot /home/client/public_html/

     XSendFile On
     XSendFilePath /home/client/storage

     WSGIScriptAlias / /home/client/application/django.wsgi
     <Directory /home/client/application>
         Order allow,deny
         Allow from all

     Alias /robots.txt /home/client/public_html/robots.txt
     Alias /favicon.ico /home/client/public_html/favicon.ico
     Alias /images /home/client/public_html/images
     Alias /static /home/client/public_html/static
     Alias /admin_media /home/client/public_html/admin_media

     ErrorLog /home/client/logs/error.log
     CustomLog /home/client/logs/access.log combined

Enable the xsendfile by using this command:

$> sudo a2enmod xsendfile

Then restart apache.

$> sudo /etc/init.d/apache2 restart

What it will look like in your views.py

def download(request,filename):
    Download a file
    "filename" must be a full path: /path/to/my/file.txt
    #It's a good idea to check if the user is allowed access to the file here.
    response = HttpResponse(mimetype='application/force-download') 
    response["X-Sendfile"] = filename
    response['Content-length'] = os.stat(filename).st_size
    return response

ubuntu forums

This entry was posted in General and tagged , , , . Bookmark the permalink.

2 Responses to Apache mod_xsendfile for my Django app (UPDATED)

  1. Asker says:

    Thank you! Wery nice blog :-)

  2. Pingback: eKini Web Developer Blog » Django: Reading an image outside the public accessible directory and displaying the image through the browser

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>