Django 和 Nginx X-accel-redirect [英] Django and Nginx X-accel-redirect

查看:22
本文介绍了Django 和 Nginx X-accel-redirect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我一直在摸索着试图保护 Django 的媒体文件,但没有成功!我只是想让它只有管理员用户可以访问媒体文件夹.这是我的 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 设置中将/media/添加到根 URL 的末尾.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆