Search code examples
phpnginxsubdomain

"File not found" when change root in config nginx


I want to config auto create subdomain for my domain:

example.com -> source in /www/source/
abcd.example.com -> source in /www/source/abcd/

I was using this configuration:

server {
        listen 80; 
            server_name   ~^(.*)\.example\.com$; 
            # If a directory doesn't exist...
            if (!-d /www/source/$1) {
                rewrite . example.com redirect;
            }    
            # Sets the correct root
            root /www/source/$1;
            location ~* \.php$ {
                fastcgi_index   index.php;
                fastcgi_pass    127.0.0.1:9000;
                include         fastcgi_params;
                fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
                fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
            }
        }

In /www/source/abcd/, I have index.php. But it is not run. When I go to abcd.example.com I get "File not found." I replaced index.php to index.html, and then it runs correctly.

How can fix that?


Solution

  • Use a named capture as numeric captures can go out of scope.

    For example:

    server_name  ~^(?<subdomain>.*)\.example\.com$; 
    root /www/source/$subdomain;
    

    See this document for more.