Nginx – Regular expressions in server_name with Nginx vhost

nginxregexsubdomainvirtualhost

I have something I'm trying to do with Nginx. Say I have a few users and a subdomain, and each user has a directory at /home/dev/sites/USER_ID. I would like for USER_ID.dev.example.com to point to that directory.

I've tried making a vhost files as follows:

server {
    listen   80;
    server_name ~^(?<site_id>)$.dev.example.com;
    root   /home/dev/sites/$site_id;
    index  index.php;

    location / {
        try_files $uri $uri/ /index.php?$uri&$args;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass    127.0.0.1:9000;
        fastcgi_index   index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

However, all that's happening is that it's showing the PhpMyAdmin installation I have (obviously another vhost is pointing it there).
Can someone tell me what I'm doing wrong? I have a feeling it's just bad Regex, but I'm not sure.

Best Answer

That expression will never match, since $ is in the middle of the string. Try:

server_name ~^(?<site_id>.+)\.dev\.example\.com$;