Django和Nginx X-accel-redirect [英] Django and Nginx X-accel-redirect
问题描述
到目前为止,我一直在摸索尝试保护Django的媒体文件而没有运气!我只是想让只有管理员用户才能访问media文件夹的地方.这是我的Nginx文件.
I have been fumbling around with trying to protect Django's media files with no luck so far! I am simply trying to make it where ONLY admin users can access the media folder. Here is my Nginx file.
server {
listen 80;
server_name xxxxxxxxxx;
location = /favicon.ico {access_log off; log_not_found off;}
location /static/ {
alias /home/{site-name}/static_cdn/;
}
location /media/ {
internal;
root /home/{site-name}/;
}
location / {
this is setup and working. Didn't include Code though
}
我的网址文件
urlpatterns = [
url(r'^media/', views.protectedMedia, name="protect_media"),
]
我的观点
def protectedMedia(request):
if request.user.is_staff:
response = HttpResponse()
response['Content-Type'] = ''
response['X-Accel-Redirect'] = request.path
return response
else:
return HttpResponse(status=400)
这将产生404 Not Found Nginx错误.这里有什么公然错误的地方吗?谢谢!
This is producing a 404 Not Found Nginx error. Does anything look blatantly wrong here? Thanks!
顺便说一句,我尝试在Nginx设置的根URL末尾添加/media/.
BTW, I have tried adding /media/ to the end of the root URL in the Nginx settings.
推荐答案
感谢@Paulo Almeida,这就是解决此问题的方法.
This is what fixed this issue thanks to @Paulo Almeida.
在nginx文件中,我也更改了以前的内容...
In the nginx file I changed what I previosly had too...
location /protectedMedia/ {
internal;
root /home/{site-name}/;
}
我的网址是...
url(r'^media/', views.protectedMedia, name="protect_media"),
视图是...
def protectedMedia(request):
if request.user.is_staff:
response = HttpResponse(status=200)
response['Content-Type'] = ''
response['X-Accel-Redirect'] = '/protectedMedia/' + request.path
return response
else:
return HttpResponse(status=400)
这很好用!现在,只有管理员用户可以访问存储在我的媒体文件夹中的媒体文件.
This works perfectly! Now only admin users can access the media files stored in my media folder.
这篇关于Django和Nginx X-accel-redirect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!