Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 875
Frozenskys Avatar asked Feb 12 '10 22:02

Frozenskys


1 Answers

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;
  }
}
like image 57
blueyed Avatar answered Sep 30 '22 16:09

blueyed