Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
Django: Restrict static folder access to non logged-in users

I am trying to restrict those users, who directly hit on a absolute static image url path(www.xyz.com/static/img/sam.png) in browser and access it.

I tried with the following django docs:

https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/apache-auth/

But this will block those images which are there in login page also(before valid user is authenticated).

Is there any other efficient way to do restrict non logged-in users?

EDIT: I had referred to this Django: Serving Media Behind Custom URL but it is related to nginx and not apache. And also there is a difference b/w static and media content. My question is related to just static content

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

you can try my answer here by just routing static url request to your own view (it tries to use sendfile extension available in almost all web servers) or use django whitenoise, whitenoise uses sendfile api which is server independent ( whether you are using nginx or apache) and production ready, extend the whitenoise middleware and add your checking there for file restriction, a sample code will be

  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")

NOTE: Serving files directly ( large files ) using python file chunks api is not a good idea when you are in production ( ideas like file.read() or FileResponse)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!