[Answered ]-Serving protected files with Django and Nginx X-accel-redirect

2👍

Should I not be reading the file with open(),

That’s correct. Your script shouldn’t be opening the file. You just tell Nginx where the file exists and let it open the file and serve it.

I believe you want to just return an empty response after setting the appropriate headers

return HttpResponse('', mimetype=contenttype)

In PHP I setup the Nginx accel redirect by doing:

//Set content type and caching headers
//...
header("X-Accel-Redirect: ".$filenameToProxy);
exit(0);

i.e. exiting immediately after setting the header.

For the continuing 404 problem, you’ve probably got an error in the Nginx conf, but you need to post the rest to be sure. Your external URL appears to be something like:

static_files/downloads/protected-test/(?P<filename>.+)$

This will be matched on:

location ~ ^.*/protected-test/ {
    alias /<path-to-my-protected-files-on-server>/;
    internal;
}

giving the 404.

There is no need (and it’s quite confusing) to have the same word protected-test in both the external URL and internal URL. I’d recommend not doing that i.e. have the external URL be like:

/static_files/downloads/(?P<filename>.+)$

Then have the internal location block be:

location ~ ^/protected-test {
    alias /<path-to-my-protected-files-on-server>;
    internal;
}

And then when you setup the x-accel-redirect header, swap between the two:

external_path = "/static_files/downloads";
nginx_path = "/protected-test";
filenameToProxy = str_replace(external_path, nginx_path, full_path);
header("X-Accel-Redirect: ".$filenameToProxy);

Rather than having the word protected-test be on both sides of the request.

👤Danack

Leave a comment