Login

Apache X-sendfile with permissions checking

Author:
h0axify
Posted:
March 31, 2012
Language:
Python
Version:
1.3
Tags:
http media static xsendfile
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. Custom mod_python AuthenHandler by aeby 7 years, 8 months ago
  2. Use the WSGIAccessScript Directive to secure static files based on the Django session by LuckiDog 3 years, 11 months ago
  3. Serve static media and indexes from app directories [Python2.5, Development only] by adamlofts 6 years, 8 months ago
  4. Python fixup handler for Apache by ofalk 5 years, 10 months ago
  5. Copy media files to central location for easier sharing by jtiai 5 years, 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.