我试图限制那些直接在浏览器中点击绝对静态图像 url 路径 (www.xyz.com/static/img/sam.png) 并访问它的用户。
我尝试使用以下 Django 文档:
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/apache-auth/
但这也会阻止登录页面中的那些图像(在验证有效用户之前)。
有没有其他有效的方法来限制未登录用户?
编辑: 我提到过这个 Django: Serving Media Behind Custom URL但它与 nginx 有关,与 apache 无关。 黑白静态内容和媒体内容也有区别。我的问题只与静态内容有关
最佳答案
你可以试试我的回答here通过将 static
url 请求路由到您自己的 View (它尝试使用几乎所有 Web 服务器中可用的 sendfile 扩展名)或使用 django whitenoise , whitenoise 使用独立于服务器的 sendfile api(无论你使用的是 nginx 还是 apache)并且生产就绪,扩展 whitenoise middleware
并在那里添加你的文件限制检查,一个 sample
代码将是
from django.http import HttpResponseForbidden
from whitenoise.middleware import WhiteNoiseMiddleware
# this is a sample code, you can change for your use case
class ProtectedStaticFileMiddleware(WhiteNoiseMiddleware):
def process_request(self, request):
# check user authentication
if condition_met(request):
return super(WhiteNoiseMiddleware, self).process_request(request)
# condition false
return HttpResponseForbidden("you are not authorized")
注意:在生产中使用 python 文件 block api 直接提供文件(大文件)不是一个好主意(像 file.read() 或 FileResponse 这样的想法)
关于python - Django:限制非登录用户访问静态文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43271275/