如何在Nginx服务器块中使用匹配的位置作为变量?

如何在Nginx服务器块中使用匹配的位置作为变量?,nginx,url-rewriting,Nginx,Url Rewriting,我有如下nginx服务器配置: server { listen 80; listen [::]:80; root /var/www/html; index index.php index.html index.htm; server_name example.com www.example.com; location /project1/public { try_files $uri $uri/ /project1/public/index.php?$query

我有如下nginx服务器配置:

server {
  listen 80;
  listen [::]:80;
  root /var/www/html;
  index index.php index.html index.htm;
  server_name example.com www.example.com;

  location /project1/public {
    try_files $uri $uri/ /project1/public/index.php?$query_string;
  }

  location /project2/public {
    try_files $uri $uri/ /project2/public/index.php?$query_string;
  }

  location /project3/public {
    try_files $uri $uri/ /project3/public/index.php?$query_string;
  }

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
  }
}
它是有效的。但是,当我尝试使用下面的正则表达式代码来动态执行此操作时,它会下载URL,而不是在浏览器中显示URL

server {
  listen 80;
  listen [::]:80;
  root /var/www/html;
  index index.php index.html index.htm;
  server_name example.com www.example.com;

  location ~ ^/([^/]+)/public {
    try_files $uri $uri/ /$1/public/index.php?$query_string;
  }

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
  }
}

有什么想法吗?

试着改变位置块的顺序

如果在中检查位置块的顺序/优先级,则有两条规则对配置非常重要:

如果Nginx找到像/project1/public这样的常规位置块,它不会停止搜索,任何正则表达式和任何更长的常规块将首先匹配

->因此,在您的第一个配置中,Nginx首先激发您的php regex位置,然后执行try\u文件

正则表达式将按其在配置文件中的出现顺序进行检查。正则表达式的搜索在第一次匹配时终止,并使用相应的配置

->在第二个配置中,由于首先找到try_文件,因此从未使用过php正则表达式