nginx - two subdomain configuration

I'm new to Nginx and I'm trying to get subdomains working.

What I would like to do is take my domain (let's call it example.com) and add:

  • sub1.example.com,
  • sub2.example.com, and also have
  • www.example.com available.

I know how to do this with Apache, but Nginx is being a real head scratcher.

I'm running Debian 6.

My current /etc/nginx/sites-enabled/example.com:

server {
    server_name www.example.com example.com;
    access_log /srv/www/www.example.com/logs/access.log;
    error_log /srv/www/www.example.com/logs/error.log;
    root /srv/www/www.example.com/public_html;

    location / {
        index  index.html index.htm;
    }

    location ~ \.php$ {
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    }
}

It is working to serve example.com and www.example.com.

I have tried to add a second server block in the same file like:

server {
        server_name www.example.com example.com;
        access_log /srv/www/www.example.com/logs/access.log;
        error_log /srv/www/www.example.com/logs/error.log;
        root /srv/www/www.example.com/public_html;

        server {
            server_name sub1.example.com;
            access_log /srv/www/example.com/logs/sub1-access.log;
            error_log /srv/www/example.com/logs/sub1-error.log;
            root /srv/www/example.com/sub1;
    }
        location / {
            index  index.html index.htm;
        }

        location ~ \.php$ {
            include /etc/nginx/fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
        }
}

No luck. Any ideas? I'd super appreciate any feedback.


Solution 1:

The mistake is putting a server block inside a server block, you should close the main server block then open a new one for the sub domains

server {
    server_name example.com;
    # the rest of the config
}
server {
    server_name sub1.example.com;
    # sub1 config
}
server {
    server_name sub2.example.com;
    # sub2 config
}

Solution 2:

You just need to add the following line in place of your server_name

server_name xyz.com  *.xyz.com;

And restart Nginx. That's it.