Search code examples
nginxsubdomainmod-rewriteurl-rewriting

Complex nginx rewrite rules for subdomains


I currently have the following (hacky) re-write rule in my nginx.conf to allow dynamic sub-domains to be re-directed to one Django instance.

set $subdomain "";
set $subdomain_root "";
set $doit "";
if ($host ~* "^(.+)\.domain\.com$") {
    set $subdomain $1;
    set $subdomain_root "/profile/$subdomain";
    set $doit TR;
}
if (!-f $request_filename) {
    set $doit "${doit}UE";
}
if ($doit = TRUE) {
    rewrite ^(.*)$ $subdomain_root$1;
    break;
}

I'm sure there is a more efficient way to do this but I need to change this rule so that any requests to *.domain.com/media/* or *.domain.com/downloads/* go to domain.com/media/* and domain.com/downloads/*.


Solution

  • Actually I think it is much easier to change the nginx re-write rules than to write middleware for django to do this. After reading up on how nginx processes it's location matching (most exact -> least exact) I created locations for /media and /download as well as a catch all location for / I then moved the rewrite rule to under the / location and simplified it - as I'm no longer worried about checking for files because this entire location is passed to django - the rule becomes :

    set $subdomain "";
    set $subdomain_root "";
    if ($host ~* "^(.+)\.domain\.com$") {
        set $subdomain $1;
        set $subdomain_root "/profile/$subdomain";
        rewrite ^(.*)$ $subdomain_root$1;
        break;
    }
    

    and would probably be even simpler if my nginx\regex scripting was better :)