Migrating an application with subdomains to a single URL

52 views Asked by At

I currently have an application that uses django-tenants with subdomains for each tenant (tenant1.domain.com, tenant2.domain.com...) It uses individual authentication, the auth models are in the schemas So my question is: Is it possible to migrate to a single URL model both for authentication and navigation?

I tried many solutions, some managed to authenticate my user, but none managed to make me navigate in a tenant using a "schema-free" URL In short none maintained/created a session

1

There are 1 answers

1
Ahmet Deger On

You can partially address this issue using NGINX configuration, particularly for managing the routing and handling of subdomains to URLs. However, certain aspects like authentication, session management, and database schema changes will still need to be handled within your Django application.

  1. Domain to URL Mapping:

In your NGINX configuration, you can set up a server block for your main domain (e.g., domain.com) and use a wildcard server name to capture all subdomains. Inside this server block, you can configure NGINX to rewrite the URLs based on the subdomain. For example:

server {
    listen 80;
    server_name ~^(?<subdomain>.+)\.domain\.com$;
    location / {
        proxy_set_header Host domain.com;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://backend-server/$subdomain$request_uri;
    }
}

In the above example, NGINX captures the subdomain using a regular expression and then passes it to the backend server as a part of the rewritten URL.

  1. Backend Configuration:

In your Django application, you will need to modify your URL routing to handle URLs based on the captured subdomain. This means your views and models should be aware of the tenant based on the URL.

  1. Session and Authentication:

While NGINX can handle URL routing, handling authentication, and session management are typically the responsibility of your Django application. You will need to update your Django authentication logic to work with the URL-based tenant identification.

  1. Database Schema:

As mentioned earlier, you may need to adjust your database schema to handle a shared database with a tenant_id field. This is primarily a Django application code change and is not something NGINX can directly handle.

In summary, NGINX can help with the URL routing part by translating subdomains into URLs, but it doesn't handle authentication, session management, or database schema changes. These aspects require modifications in your Django application code. Additionally, thorough testing and potentially gradual deployment are essential to ensure a smooth transition.