2017-08-24 8 views
1

これまでのところDjangoのメディアファイルを保護しようとしていたのです!私は単に管理者のユーザーだけがメディアフォルダにアクセスできる場所にしようとしています。ここに私のNginxファイルがあります。DjangoとNginx X-accelリダイレクト

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 

} 

マイURLファイル

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見つからないnginxのエラーを生成しています。何かここで露骨に間違って見える?ありがとう!

ところで、私は/ media /をNginx設定のルートURLの最後に追加しようとしました。

+0

あなたの設定を見て、問題はこの回答で特定されているようです:https://stackoverflow.com/a/45774975/1081569保護されたビューには、nginx構成のものと同じURLを使用できません。 –

+0

ありがとう、@PauloAlmeida。あなたが私に送ったリンクにいくつか変更を加えて、それを稼働させることができました! –

答えて

1

@Paulo Almeidaのおかげで、これがこの問題を解決しました。私はprevioslyすぎていたものに変更nginxのファイルで

...

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

私のURLは...

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) 

これは完全に機能します!管理者だけが自分のメディアフォルダに保存されているメディアファイルにアクセスできます。

関連する問題