Nginx – Serving files with nginx and django

djangonginx

I'm trying to serve protected files with nginx using X-Accel-Redirect header by following this tutorial (and many others).

physical path: /home/media/file.pdf

url: example.com/media/file.pdf

nginx configuration:

location /media/ {
    internal;
    alias /home/;
}

In django I have a middleware, which checks if user is authenticated and if so, uses the X-Accel-Redirect for nginx to pass the file:

response["X-Accel-Redirect"] = request.path

When I try to access the file I'm getting 404 error (requested file path is OK in access log). Seems to me that nginx won't pass the request to django and just ends with 404 error.

Any idea what I might be doing wrong? Is there a good way to debug this?
Thanks in advance.

Best Answer

The problem is the difference between alias and root. With alias as you have it defined, the URI /media/file.pdf will map to the physical location /home/file.pdf.

You need to use root:

location /media/ {
    internal;
    root /home;
}

See this and this for details.

Related Topic