Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Working on migrating servers and having zero luck setting up my subdomains. The behavior I'm looking for is fairly straightforward:

  • & --> /var/www/live/
  • * --> /var/www/*/ (assuming the sub directory exists, otherwise redirect to main site)

I've tried using $host in a couple of configurations and I've tried using many variations of:

server_name ~^(.*)\.domain\.com$;

root /var/www/$1;


server_name ~^(?<subdomain>.+)\.domain\.com$;

root /var/www/$subdomain;

This is basic NginX behavior but I'm completely stumped and I've wasted way too many hours trying to hack my way through this. Can anyone shed some light on the solution?

Thanks in advance!

share|improve this question
Note that using $host in this way will cause the variable to be evaluated at every request. If you have a static number of subdomains, consider writing vhosts. – gparent May 18 '12 at 14:26

try this:

server {
    listen 80;
    server_name *;
    root /var/www/$subdomain;
    set $subdomain "";
    if ($host ~* ^([a-z0-9-\.]+)\$) {
        set $subdomain $1;
    if ($host ~* ^(www.)?$) {
        set $subdomain "live";

share|improve this answer
No dice, but I'll try to play with a couple variations of this. – Peter Hanneman May 18 '12 at 14:55

Your second server_name directive looks correct and should work (and is the nicest solution IMHO). The documentation suggests the following syntax for older PCRE versions, so you could try this:

server_name ~^(?P<subdomain>.+)\.domain\.com$;
root /var/www/$subdomain;
share|improve this answer

Other people are using map to help solve this problem. Here are direct docs for map.

Some other things to check: Check the version of you Nginx you are using against the latest version. If you are reading the documentation online, they may be referencing newer behaviors than the ones you actually having.

Also, it's my understanding that the backreference syntax like ?<subdomain> is enabled in part from libpcre. Check man pcrepattern and see if it has a section on "NAMED SUBPATTERNS".

share|improve this answer
I have complied NginX 1.2.0 with the latest PCRE library. Map looks promising - I'm reading up on it now. – Peter Hanneman May 18 '12 at 14:58
this variant have an advantage of using txt file for cname->username association. But it also will be slightly slower under load. – DukeLion May 18 '12 at 14:58

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.