3

Considering I have something like this:

    /sites/foo/a1
    /sites/foo/a2
    /sites/foo/a3
    /sites/bar/b1
    /sites/bar/b2

And I want to access them like this:

foo.a1.mydomain.com

or (if the last one doesn't work)

foo-a1.mydomain.com

How can I create virtual hosts dynamically in nginx, to accept going to those folders?

1
  • "I" is always capital case in English.
    – peterh
    Nov 10, 2015 at 17:31

1 Answer 1

4
+25

This can be accomplished by the following nginx conf:

server {
    listen 80;
    server_name mydomain.com *.mydomain.com;
    set $path "default";
    if ($host ~* ^([a-z0-9-]+)\.([a-z0-9-]+)\.mydomain.com$) {
        set $path "$1/$2";
    }
    root /sites/$path;
}

Nginx sets the $path variable according to the groupings in the regular expression matched against the $host variable, which is automatically set by nginx (see Embedded Variables). By initially setting $path to "default", you can serve content from the /sties/default directory in the event that $host doesn't match the regex.

Alternatively, you can use regex matching in the server_name directive. See Nginx Server Names for more info.

2
  • Although the code is appreciated, it should always have an accompanying explanation. This doesn't have to be long, but it is expected.
    – peterh
    Nov 10, 2015 at 17:30
  • @peterh, fair enough; edited.
    – xofer
    Nov 10, 2015 at 17:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .