Nginx – Wildcard vhosts on Nginx

nginxsubdomainvirtualhostwildcard

I've just installed Nginx on my server and am extremely happy with the results, however I still cannot figure out how to insert wildcard virtual hosts.

This is the [directory] structure I'd like:

-- public_html (example.com)
---subdoamin 1 (x.example.com)
---subdomain 2 (y.example.com)

As you can see it's pretty basic, however, I'd like the ability to add domains by simply adding an A record for a new subdomain, which will instantly point to the subdirectory of the same name under public_html.

There's stuff on the web, however I haven't come across something exactly like this.

Any help would be greatly appreciated.

Best Answer

I shall show you.

The configuration file

server {
  server_name example.com www.example.com;
  root www/pub;
}

server {
  server_name ~^(.*)\.example\.com$ ;
  root www/pub/$1;
}

Test files

We have two test files:

$ cat www/pub/index.html 
COMMON

$ cat www/pub/t/index.html 
T

Testing

Static server names:

$ curl -i -H 'Host: example.com' http://localhost/
HTTP/1.1 200 OK
Server: nginx/0.8.54
Date: Wed, 23 Mar 2011 08:00:42 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Wed, 23 Mar 2011 07:56:24 GMT
Connection: keep-alive
Accept-Ranges: bytes

COMMON

$ curl -i -H 'Host: www.example.com' http://localhost/
HTTP/1.1 200 OK
Server: nginx/0.8.54
Date: Wed, 23 Mar 2011 08:00:48 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Wed, 23 Mar 2011 07:56:24 GMT
Connection: keep-alive
Accept-Ranges: bytes

COMMON

And regexp server name:

$ curl -i -H 'Host: t.example.com' http://localhost/
HTTP/1.1 200 OK
Server: nginx/0.8.54
Date: Wed, 23 Mar 2011 08:00:54 GMT
Content-Type: text/html
Content-Length: 2
Last-Modified: Wed, 23 Mar 2011 07:56:40 GMT
Connection: keep-alive
Accept-Ranges: bytes

T