系统相关
首页 > 系统相关> > Django和Nginx X-accel-redirect

Django和Nginx X-accel-redirect

作者:互联网

到目前为止,我一直在努力保护Django的媒体文件而无所事事!我只是想让它只在管理员用户可以访问媒体文件夹的地方.这是我的Nginx文件.

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错误.这里看起来有什么明显的错误吗?谢谢!

顺便说一句,我已经尝试在Nginx设置中将/ media /添加到根URL的末尾.

解决方法:

这就是@Paulo Almeida解决这个问题的原因.

在nginx文件中,我改变了我以前所拥有的…

   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)

这很完美!现在只有管理员用户可以访问我的媒体文件夹中存储的媒体文件.

标签:nginx,django,ubuntu,sendfile,django-media
来源: https://codeday.me/bug/20191008/1871593.html