Subdomain routing in django application

I have a django project that's hosted on a custom domain (e.g. mydomain.com). I have "app" app. For example, in development, requests looked like mydomain.com/app/dashboard. However, I wanted to use a subdomain instead so that my entire app is hosted on the subdomain app.mydomain.com and requests to mydomain.com/app/dashboard would route to app.mydomain.com/dashboard. I am using Nginx to handle this but I'm running into a few problems. Main part of nginx config:

server {
    listen 443 ssl;
    server_name mydomain.co www.mydomain.co;

    location ~ ^/app(/?)(.*)$ {
        return 301 https://app.mydomain.co/$2;
    }

    location ~ ^/help(/?)(.*)$ {
        return 301 https://help.mydomain.co/$2;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        # WebSocket specific headers
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}
server {
    listen 443 ssl http2;
    server_name app.mydomain.co;

    location / {
        # Proxy to your Django application server
        proxy_pass http://127.0.0.1:8000; # Adjust the port to match your setup
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
# same for help

When my url pattern is like this:

    path('app', include('app.urls')),

and I try to access the dashboard it redirects to app.mydomain.com/dashboard which is not valid since /dashboard is a url exclusively for /app and not the root directory. Then when I modified it to:

path('', include('app.urls')),

this worked but then my urls for "app" were available to other subdomains (for example, a user was able to access help.mydomain.com/dashboard and still see the dashboard and my entire app on this subdomain). Any help would be appreciated. Thanks.

Back to Top