【发布时间】:2013-04-19 21:14:48
【问题描述】:
我正在尝试让 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
我的设置文件中有 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>
所以,如果我尝试访问:
<domain-name>/static_files/downloads/protected-test/<filename>
在我的浏览器窗口中,它不允许 (404)。很好。
但是 - 如果我尝试从我想要允许的表单下载访问该 url,我会在浏览器中获得重定向到:
<domain-name>/protected-test/<filename>
它也是一个 404。
我尝试了很多不同的配置,现在我的大脑很疼。 :-)
我不应该用 open() 读取文件,让 Nginx 服务它吗?如果我删除该行,它会返回一个包含可怕的零字节的文件。为什么我仍然在重定向的 url 上得到 404??
【问题讨论】:
标签: django nginx x-accel-redirect