Login

Apache X-sendfile with permissions checking

Author:
h0axify
Posted:
March 31, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

This allows the mod_xsendfile module for Apache safely serving private files. Django take cake about processing and permissions checking, Apache server requested files.

Installation of mod_xsendfile:

$ tar -xzvf mod_xsendfile-0.12.tar.gz $ /usr/sbin/apxs -c mod_xsendfile-0.12/mod_xsendfile.c $ ld -Bshareable -o mod_xsendfile-0.12/mod_xsendfile.so mod_xsendfile-0.12/mod_xsendfile.o

Copy mod_xsendfile.so to your local Apache modules folder. Modify httpd.conf to load an enable the module:

LoadModule xsendfile_module modules/mod_xsendfile.so

Add to virtual host container: <Virtual ...:80> XSendFile On XSendFilePath /home/django_projects/mysite/media/ </Virtual>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Add to urls.py:
urlpatterns += patterns('',
    url(r'^media\/(?P<path>.*)$', 'views.media_xsendfile', {
        'document_root': settings.MEDIA_ROOT,
    }),
)


Add to views.py:
from django.conf import settings
from django.http import HttpResponse
from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
def media_xsendfile(request, path, document_root):
    response = HttpResponse()
    response['Content-Type'] = ''
    response['X-Sendfile'] = (os.path.join(settings.MEDIA_ROOT, path)).encode('utf-8')
    return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

btimby (on April 3, 2012):

Along with UTF-8 encoding, you should use URL encoding.

https://github.com/nmaier/mod_xsendfile/commit/0efcd03ac196930da6b139b77972c0d430e0225c

This way any non-ASCII chars can be safely sent via the HTTP header (which must be 7 bit values).

response['X-Sendfile'] = urllib.quote(os.path.join(settings.MEDIA_ROOT, path).encode('utf-8'))

#

MechanisM (on April 4, 2012):

Same for nginx but: X-Accel-Redirect instead of X-Sendfile

#

Please login first before commenting.