""" Custom middleware for host-based URL routing. Routes requests based on hostname: - *.rfiles.online (subdomains) → shared space portal - rfiles.online / www.rfiles.online → main upload portal """ import re from django.urls import set_urlconf import logging logger = logging.getLogger(__name__) class HostBasedURLConfMiddleware: """ Middleware that switches URL configuration based on the request host. - rfiles.online / www.rfiles.online -> config.urls (main portal) - *.rfiles.online -> config.urls_shared_space (shared space portal) """ RFILES_SUBDOMAIN_PATTERN = re.compile(r'^([a-z0-9-]+)\.rfiles\.online$') def __init__(self, get_response): self.get_response = get_response def __call__(self, request): host = request.get_host().split(':')[0].lower() # Reset any previous shared space context request.shared_space_slug = None # Check for rfiles.online subdomain pattern match = self.RFILES_SUBDOMAIN_PATTERN.match(host) if match: subdomain = match.group(1) if subdomain not in ('www', 'direct'): request.shared_space_slug = subdomain request.urlconf = 'config.urls_shared_space' set_urlconf('config.urls_shared_space') logger.info(f"Using shared space URLs for host: {host}, slug: {subdomain}") response = self.get_response(request) set_urlconf(None) return response # All other hosts (rfiles.online, www.rfiles.online, localhost) → main portal request.urlconf = 'config.urls' set_urlconf('config.urls') response = self.get_response(request) set_urlconf(None) return response