启用PHP的Nginx通配符子域

我正在使用Laravel / PHP将Nginx设置为几个不同项目的临时服务器。 这个想法是在/var/www我将有不同数量的子目录,每个子目录都以subdomain.example.com格式访问。

考虑一下这个非常简单的Nginxconfiguration:

 server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; index index.html index.htm; server_name ~^(.*)\.example\.com$; root /var/www/$1; } 

我有我的目录结构设置为:

 /var/www /subdomain1 /subdomain2 /subdomain3 

如果我访问subdomain1.example.comsubdomain2.example.comsubdomain3.example.com则会提供相关子目录中的index.html文件。 迄今为止都是完美的。

当我尝试使用PHP文件工作时,问题出现了。 首先,我改变索引指令index index.php ,然后在server指令中添加以下内容:

  location ~ \.php$ { try_files $uri /index.php =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } 

Nginx接受这个configuration没有任何问题。 但是,如果我尝试访问subdomain1.example.com然后我从Nginx得到一个404错误,但没有什么在错误日志中。

如果我将try_files指令更改为try_files $uri /subdomain1/index.php =404; 那么它会正确地执行subdomain1目录中的index.php文件,但是这显然违背了目的,因为我希望它能够作为通配符工作。 问题是我没有访问位置指令中父指令的$ 1variables。

我觉得我必须在这里错过一些很明显的东西。 任何人?

我认为我之前已经看到过这种情况, root有一个后期绑定,数字捕获超出了范围。 尝试使用命名的捕获。 就像是:

 server { ... server_name ~^(?<subdomain>.+)\.example\.com$; root /var/www/$subdomain; index index.php; location / { try_files $uri $uri/ /index.php; } location ~ \.php$ { try_files $uri /index.php; ... } }