我正在尝试使用django 2.0为受保护的媒体文件提供nginx sendfile和x-accel-redirect。
这是我的nginx配置:
server {
listen 8000;
server_name localhost;
charset utf-8;
sendfile on;
# Protected media
location /protected {
internal;
alias /Users/username/Documents/sat23/venv/media/;
}
# Django static
location /static {
alias /Users/username/Documents/sat23/venv/static/;
}
# All other requests.
location / {
uwsgi_pass django;
include /Users/username/Documents/sat23/venv/uwsgi_params;
}
}
然后,在我的urls.py中,我添加了一个简单的视图,它应该为我的媒体文件提供服务(稍后我将配置权限):
def serveMedia(request):
url = request.path.replace('media', 'protected')
response = HttpResponse('')
response['X-Accel-Redirect'] = url
response['Content-Type'] = ''
return response
urlpatterns += [
path('/media/', serveMedia, name='protected_media')
]
但是每次我打电话
localhost:8000/media/users/user35.jpg
我刚得到一个django(不是nginx)404页,说django尝试了所有配置的路径,但找不到请求的路径。
所以我怀疑我的观点是行不通的。然后我这样重写:
def serveMedia(request):
return HttpResponse(content=b'Hello there')
当然,它不会被呼叫。但我不知道为什么。有人能帮我吗?
另外,关于配置nginx conf的任何建议也非常欢迎!