Search code examples
djangonginxuwsgi

Make django handle subdomain suffix


We're hosting several dockerized web-apps on our webserver, let's call it group.example.com. Our subdomains are handled via nginx as suffixes though, which translates to something like group.example.com/app1/ group.example.com/app2/ as root urls.

When using Django, we run into problems though, as all its urls generated by url in the templates such as <a href="{% url 'index' %}">home</a> will be relative links, so rendered to <a href="/">home</a>. This relative link will not be interpreted correctly, leading to the main, non-app page group.example.com.

So the goal is to have an app based prefix such as /app1/ for all links. I can hardcode these for static links, but there has to be a more elegant way. Also this leads to problem for the used forms submitting to the wrong page - redirecting again back to the main, non-app page group.example.com.

I tried adding /app1/ to all registered urls as prefix, but that doesn't seem to work either - that way the app is running but user would need to visit group.example.com/app1/app1/ to get to the index, and the relative links still don't work correctly.

In the app docker-container we're running the web-app with nginx and uwsgi. It works fine when using correct subdomains such as app1.example2.com - but we don't have that capability on our new faster webserver we want to host the app on.

Is there a way to resolve this using the app containers nginx, uwsgi or django / middleware config to get the links to resolve to group.example.com/app1/ as root?


Solution

  • As far as I know, there is two ways to resolve it.

    One use SCRIPT_NAME in the NGINX configuration. For example, based on this server fault answer:

    location /app1/ {
        SCRIPT_NAME /app1;
        # rest of the config
    }
    

    Two You can add FORCE_SCRIPT_NAME in your settings.py:

    FORCE_SCRIPT_NAME = '/app1'
    

    FYI, I would prefer using first solution.