Django和Nginx X-accel-redirect

Tyl*_*ell 3 django ubuntu nginx sendfile django-media

到目前为止,我一直在摸索尝试保护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

}
Run Code Online (Sandbox Code Playgroud)

我的网址文件

urlpatterns = [
    url(r'^media/', views.protectedMedia, name="protect_media"),
] 
Run Code Online (Sandbox Code Playgroud)

我的看法

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)
Run Code Online (Sandbox Code Playgroud)

这将产生404 Not Found Nginx错误。这里有什么公然的错误吗?谢谢!

顺便说一句,我尝试在Nginx设置的根URL末尾添加/ media /。

Tyl*_*ell 8

感谢@Paulo Almeida,这就是解决此问题的方法。

在nginx文件中,我也更改了以前的内容...

   location /protectedMedia/ {
          internal;
          root /home/{site-name}/;
   }
Run Code Online (Sandbox Code Playgroud)

我的网址是...

url(r'^media/', views.protectedMedia, name="protect_media"),
Run Code Online (Sandbox Code Playgroud)

视图是...

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)
Run Code Online (Sandbox Code Playgroud)

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


fin*_*uss 8

这对我帮助很大,只是一个小的更新和修改:

\n

网址.py:

\n
re_path(r\'^media/(?P<path>.*)\', protectedMedia, name="protect_media")\n
Run Code Online (Sandbox Code Playgroud)\n

视图.py:

\n
from urllib.parse import quote\nfrom django.http import HttpResponse\nfrom django.contrib.admin.views.decorators import staff_member_required\n\n\n@staff_member_required\ndef protectedMedia(request, path):\n    response = HttpResponse(status=200)\n    response["Content-Type"] = \'\'\n    response[\'X-Accel-Redirect\'] = \'/protectedMedia/\' + quote(path)\n    return response\n
Run Code Online (Sandbox Code Playgroud)\n

我必须将 nginx 配置更改为以下内容:

\n
location /protectedMedia/ {\n      internal;\n      alias /home/{site-name}/;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

笔记:

\n
    \n
  • 我更喜欢使用装饰器,因为它会自动重定向到登录页面(在设置中指定时)并设置“下一页”。
  • \n
  • url()在 Django 3.1 中已被弃用,因此只需使用re_path()即可
  • \n
  • 在 nginx 配置中使用别名而不是 root:我不想让“/protectedMedia/”出现在 url 中(并且它不起作用),另请参阅nginx 文档
  • \n
  • 2021-06-14 编辑:德语变音符号(\xc3\xa4\xc3\xbc\xc3\xb6 等)在媒体路径中不起作用,所以我编辑了上面的答案以包含来自 urllib.parse 的引用
  • \n
\n

如果您仍然卡在某个地方,这给了我更多的背景信息:https ://wellfire.co/learn/nginx-django-x-accel-redirects/

\n