使用Django和Nginx X-accel-redirect为受保护的文件提供服务

使用Django和Nginx X-accel-redirect为受保护的文件提供服务,django,nginx,x-accel-redirect,Django,Nginx,X Accel Redirect,我正试图让Nginx和Django一起玩,以提供可下载的受保护文件。我就是不能让它工作。这是我的Nginx配置: location ~ ^.*/protected-test/ { alias /<path-to-my-protected-files-on-server>/; internal; } 我的设置文件中有2个值: NGINX_ROOT = (os.path.join(MEDIA_ROOT, 'downloads/protected-test')) NGINX_URL =

我正试图让Nginx和Django一起玩,以提供可下载的受保护文件。我就是不能让它工作。这是我的Nginx配置:

location ~ ^.*/protected-test/ {
alias /<path-to-my-protected-files-on-server>/;
internal;
}
我的设置文件中有2个值:

NGINX_ROOT = (os.path.join(MEDIA_ROOT, 'downloads/protected-test'))
NGINX_URL = '/protected-test'
_convert_file_to_url()采用完整的文件路径,并使用上面的两个设置值将其转换为(我认为)Nginx允许的url:

<domain-name>/protected-test/<filename>
/protectedtest/
因此,如果我尝试访问:

<domain-name>/static_files/downloads/protected-test/<filename>
/static\u文件/下载/受保护测试/
在我的浏览器窗口中,它不允许(404)。好

但是-如果我尝试从表单下载访问该url(我希望允许),我会在浏览器中重定向到:

<domain-name>/protected-test/<filename>
/protectedtest/
它也是404

我尝试了很多不同的配置,现在我的大脑很痛。:-)

我是否应该使用open()读取文件,然后让Nginx提供服务?若我删除该行,它将返回一个包含可怕的零字节的文件。为什么我在重定向的url上仍然得到404

我是否应该使用open()读取文件

没错。您的脚本不应打开该文件。您只需告诉Nginx文件存在的位置,让它打开文件并提供服务

我相信您希望在设置适当的标题后返回一个空响应

return HttpResponse('', mimetype=contenttype)
在PHP中,我通过以下操作设置Nginx accel重定向:

//Set content type and caching headers
//...
header("X-Accel-Redirect: ".$filenameToProxy);
exit(0);
i、 e.设置收割台后立即退出

对于仍然存在的404问题,您可能在Nginx conf中遇到了一个错误,但是您需要发布其余的来确保。您的外部URL类似于:

static_files/downloads/protected-test/(?P<filename>.+)$
然后将内部位置块设置为:

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

而不是让单词
protected test
出现在请求的两边。

K,谢谢,这是一件固定的事情-但在更改后仍然无法提供文件。你能发布其余的nginx conf吗?第三方为我配置了nginx conf,我会尽快发布它。他们说这是帝王模式下的默认配置,加上上面的内部语句。不同时命名/protectedtest是个好主意,我会试试。我还注意到,您的内部配置为“~/protectedtest”,没有结束斜杠。这会和我的conf有区别吗,conf有结尾斜杠吗?它不应该-只要你的结尾在那里与否是一致的。Nginx将位置块匹配文本之后的任何内容附加到别名。因此/protectedtest/anything将映射到//anything。我认为唯一的问题可能是位置块中有斜杠,但将其保留在别名路径之外-这将无法解析为真实文件。
static_files/downloads/protected-test/(?P<filename>.+)$
location ~ ^.*/protected-test/ {
    alias /<path-to-my-protected-files-on-server>/;
    internal;
}
/static_files/downloads/(?P<filename>.+)$
location ~ ^/protected-test {
    alias /<path-to-my-protected-files-on-server>;
    internal;
}
external_path = "/static_files/downloads";
nginx_path = "/protected-test";
filenameToProxy = str_replace(external_path, nginx_path, full_path);
header("X-Accel-Redirect: ".$filenameToProxy);