2017-10-05 98 views
0

我有这样一个nginx的服务器配置:如何在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而不是在浏览器中显示它。

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; 
    } 
} 

任何想法?

回答

1

尝试更改您的位置块的顺序。

如果您在Nginx Docs检查位置块的顺序/优先级有两种规则,这对你的配置很重要:

  1. 如果Nginx的发现传统的位置块(如/project1/public),它不停止搜索任何正则表达式和长的块将被匹配的第一

    - >因此,在您第一次配置,Nginx的第一激发你的php-regex的位置,然后执行try_files

  2. 按照它们在配置文件中出现的顺序检查正则表达式。正则表达式的搜索在第一次匹配时终止,并使用相应的配置。

    - >在你的第二个配置,你php-regex因为try_files从未使用发现第一

相关问题