Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

  • www.domain.com & domain.com --> /var/www/live/
  • *.domain.com --> /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;

and

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
1  
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
add comment

3 Answers

try this:

server {
    listen 80;
    server_name example.com *.example.com;
    root /var/www/example.com/$subdomain;
    set $subdomain "";
    if ($host ~* ^([a-z0-9-\.]+)\.example.com$) {
        set $subdomain $1;
    }
    if ($host ~* ^(www.)?example.com$) {
        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
add comment

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
add comment

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
1  
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
1  
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
add comment

Your Answer

 
discard

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.