Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jerinisready/9c83fa93933a4bfe5025a8baee4e3364 to your computer and use it in GitHub Desktop.
Save jerinisready/9c83fa93933a4bfe5025a8baee4e3364 to your computer and use it in GitHub Desktop.
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.
#https://djangosnippets.org/snippets/10664/
# 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment