Login

Django nginx sendfile example

Author:
sim1234
Posted:
April 17, 2019
Language:
Python
Version:
Not specified
Tags:
django media sendfile nginx
Score:
0 (after 0 ratings)

Use nginx sendfile (X-Accel-Redirect) function to serve files but pass traffic through django. Can be used to serve media files only to logged-in users.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# views.py

from django.http import HttpResponse
from django.views.generic import View


class SendfileView(View):
    prefix = ""

    def get(self, request, path):
        response = HttpResponse()
        response["X-Accel-Redirect"] = f"{self.prefix}{path}"
        del response["Content-Type"]
        return response

# urls.py
from django.urls import re_path

urlpatterns = [
    re_path(r"^/media/(?P<path>.*)$", SendfileView.as_view(prefix="/__media__/"))
]

# nginx.conf
server {
        server_name example.com;
        listen 80;
        location /__media__/ {
                internal;
                alias /path/to/your/media/directory/;
        }
	location / {
		proxy_pass http://url.to.your.django:8000;
	}
}

More like this

Comments

Please login first before commenting.