我正在尝试让Nginx和Django一起玩,以提供可下载的受保护文件。我就是不能让它工作。这是我的Nginx配置:
location ~ ^.*/protected-test/ {
alias /<path-to-my-protected-files-on-server>/;
internal;
}用于查看文件的相关urls.py:
url(r'^static_files/downloads/protected-test/(?P<filename>.+)$', 'download_or_view',
{'download_dir': '%s%s' % (settings.MEDIA_ROOT, 'downloads/protected-test/'),
'content_disposition_type': 'inline',
'protected': 'True'},
name='protected_files')我的观点是:
def download_or_view(request, content_disposition_type, download_dir, filename=None, protected=False):
'''Allow a file to be downloaded or viewed,based on the request type and
content disposition value.'''
if request.method == 'POST':
full_path = '%s%s' % (download_dir, request.POST['filename'])
short_filename = str(request.POST['filename'])
else:
full_path = '%s%s' % (download_dir, filename)
short_filename = str(filename)
serverfile = open(full_path, 'rb')
contenttype, encoding = mimetypes.guess_type(short_filename)
response = HttpResponse(serverfile, mimetype=contenttype)
if protected:
url = _convert_file_to_url(full_path)
response['X-Accel-Redirect'] = url.encode('utf-8')
response['Content-Disposition'] = '%s; filename="%s"' % (content_disposition_type, smart_str(short_filename))
response['Content-Length'] = os.stat(full_path).st_size
return response我的设置文件中有两个值:
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>所以,如果我尝试访问:
<domain-name>/static_files/downloads/protected-test/<filename>在我的浏览器窗口中,它不允许(404)。好的。
但是-如果我尝试从表单下载访问该url,我想要允许的,我在浏览器中得到一个重定向到:
<domain-name>/protected-test/<filename>而且它也是404。
我尝试了这么多不同的配置,现在我的大脑都痛了。:-)
我不应该使用open()来读取文件,然后让Nginx来服务它吗?如果我删除这一行,它将返回一个包含可怕的零字节的文件。为什么我在重定向的url上仍然得到404??
发布于 2013-04-20 06:17:32
如果我不使用
()读取文件,
是这样的。您的脚本不应打开该文件。您只需告诉Nginx该文件所在的位置,并让它打开该文件并提供服务。
我相信在设置了适当的头之后,您只想返回一个空响应
return HttpResponse('', mimetype=contenttype)在PHP中,我通过执行以下操作来设置Nginx accel重定向:
//Set content type and caching headers
//...
header("X-Accel-Redirect: ".$filenameToProxy);
exit(0);即在设置报头之后立即退出。
对于持续的404问题,您可能在Nginx conf中得到了一个错误,但您需要发布其余内容以确保无误。您的外部URL看起来类似于:
static_files/downloads/protected-test/(?P<filename>.+)$这将在以下方面进行匹配:
location ~ ^.*/protected-test/ {
alias /<path-to-my-protected-files-on-server>/;
internal;
}给了404。
在外部URL和内部URL中没有必要(而且这很容易混淆)具有相同的单词protected-test。我建议不要这样做,即让外部URL如下所示:
/static_files/downloads/(?P<filename>.+)$然后将内部位置块设置为:
location ~ ^/protected-test {
alias /<path-to-my-protected-files-on-server>;
internal;
}然后,在设置x-accel-redirect报头时,在这两个报头之间交换:
external_path = "/static_files/downloads";
nginx_path = "/protected-test";
filenameToProxy = str_replace(external_path, nginx_path, full_path);
header("X-Accel-Redirect: ".$filenameToProxy);而不是让单词protected-test出现在请求的两边。
https://stackoverflow.com/questions/16113602
复制相似问题