Django and Nginx X-accel-redirect

后端 未结 2 1084
生来不讨喜
生来不讨喜 2020-12-10 08:04

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 folde

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 08:27

    This is what fixed this issue thanks to @Paulo Almeida.

    In the nginx file I changed what I previosly had too...

       location /protectedMedia/ {
              internal;
              root /home/{site-name}/;
       }
    

    My url is...

    url(r'^media/', views.protectedMedia, name="protect_media"),
    

    And the View is...

    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.

提交回复
热议问题