2017-10-05 77 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從未使用發現第一