Nginx: regex on server_name

English

Quick tip to use regex on nginx’s server_name directive.

Using a specific root directory for every subdomain:

1
2
3
4
5
server {
    listen 80;
    server_name ~^(.*)\.project\.com$;
    root /home/www/project/$1;
}

Using an environment variable with a single project:

1
2
3
4
5
6
server {
    listen 80;
    server_name ~^(.*)\.project\.com$;
    fastcgi_param CUSTOMER $1;
    root /home/www/project;
}

You can also use the entire domain name with this:

1
2
3
4
5
server {
    listen 80;
    server_name ~^(.*)\.(.*\..*)$;
    root /home/www/$2/subdomains/$1/public_html;
}

Tested with Nginx 1.4.x.