0

In my Django application I am using the staticfiles app in conjunction with Whitenoise.

My web server is accessible via two domains and I would like to serve different static files for each.

My idea was that www.my_domain.com/static/ would serve up, say, the files in os.path.join(BASE_DIR, "staticfiles/my_domain/"), and vice-versa for www.my_other_domain.com/static/.

What is the best way of achieving this? I have thought of three solutions:

  1. Subclass the places in which STATIC_ROOT is accessed, so that it takes the domain into account
  2. Use nginx to route www.my_domain.com/static/my_domain/ to www.my_domain.com/static/
  3. Use Django middleware to achieve the same result as 2. (like this stack overflow question)

Thank you!

biddlesby
  • 453
  • 4
  • 10
  • https://serverfault.com/questions/241005/nginx-change-root-directory-based-on-server-name – Ivan Starostin Dec 06 '18 at 13:50
  • I don't think django code has anything to do with this case - it's totally nginx related question, – Ivan Starostin Dec 06 '18 at 13:51
  • @IvanStarostin but it would be possible to do in Django code, also, no? At the moment I am running on Heroku and do not have the ability to configure it, so I'd have to additionally deploy another nginx. If there is an easy way to do it in Django it'd make my life easier. – biddlesby Dec 06 '18 at 14:03

1 Answers1

1

I would recommend using third option from your question. I would say, rather than making different static root for each site, you should keep your static root same and make two folder containing static files based on your domain. For example:

-- STATIC_ROOT
 | -- domain_a
  | -- js
  | -- css
  | -- img
 | -- domain_b
  | -- js
  | -- css
  | -- img

Add a middleware in which you can append the domain path to request:

def domain_middleware(get_response):
    def middleware(request):
        request.domain = request.META['HTTP_HOST'].split('.')[-1]
        response = get_response(request)
        return response
    return middleware

And in template, use it like this:

{% static request.domain|add:'/js/something.js' %}
ruddra
  • 50,746
  • 7
  • 78
  • 101