简体   繁体   中英

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/* .

You can use regular expression server names (see http://nginx.org/en/docs/http/server_names.html#regex_names ) and assign a matching group to a variable $subdomain directly:

server {
  listen 80;
  listen 443;
  server_name ~^(?<subdomain>.+)\.domain\.com$
  location / {
    rewrite ^ /profile/$subdomain$request_uri;
  }
}

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 :)

Perhaps a better idea would be to configure django to handle subdomains instead of adding a rewrite in your webserver. Here's how I did it: http://sharjeel.2scomplement.com/2008/07/24/django-subdomains/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM