Complex nginx rewrite rules for subdomains
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/