Py学习  »  Django

为受保护的文件nginx和django提供服务

Nikita Alexander • 5 年前 • 687 次点击  

我正在尝试使用django 2.0为受保护的媒体文件提供nginx sendfile和x-accel-redirect。 这是我的nginx配置:

server {
    listen      8000;
    server_name localhost;
    charset     utf-8;
    sendfile    on;

    # Protected media
    location /protected {
        internal;
        alias /Users/username/Documents/sat23/venv/media/;
    }

    # Django static
    location /static {
        alias /Users/username/Documents/sat23/venv/static/;
    }

    # All other requests.
    location / {
        uwsgi_pass  django;
        include     /Users/username/Documents/sat23/venv/uwsgi_params;
    }
}

然后,在我的urls.py中,我添加了一个简单的视图,它应该为我的媒体文件提供服务(稍后我将配置权限):

def serveMedia(request):
    url = request.path.replace('media', 'protected')
    response = HttpResponse('')
    response['X-Accel-Redirect'] = url
    response['Content-Type'] = ''
    return response

urlpatterns += [
    path('/media/', serveMedia, name='protected_media')
]

但是每次我打电话 localhost:8000/media/users/user35.jpg 我刚得到一个django(不是nginx)404页,说django尝试了所有配置的路径,但找不到请求的路径。

所以我怀疑我的观点是行不通的。然后我这样重写:

def serveMedia(request):
    return HttpResponse(content=b'Hello there')

当然,它不会被呼叫。但我不知道为什么。有人能帮我吗?

另外,关于配置nginx conf的任何建议也非常欢迎!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30426
 
687 次点击  
文章 [ 1 ]  |  最新文章 5 年前
AKX
Reply   •   1 楼
AKX    5 年前

你的Django中没有捕获组 path 打电话到那里,这样只会匹配 /media/ 逐字的

你可能想利用旧学校 url 使用类似regexp的路由

urlpatterns += [
    url(r'/media/.+', serveMedia),
]

捕捉一切以 /媒体/