Nginx子目錄try_files通配符總是失敗

Nginx子目錄try_files通配符總是失敗

Nginx 1.10.3 Ubuntu,標準 apt 安裝。index index.php;位於server街區外。

我需要:

  • http://example.com/test/1指向 /var/www/example.com/test/1
  • http://example.com/test/2指向 /var/www/example.com/test/2

..等等。

因為我會創建太多測試,所以我需要一個通配符try_files。目前我正在做沒有通配符的操作:

server {
    server_name example.com;
    root   /var/www/example.com;
    location /test/1/ {
        try_files $uri $uri/ /test/1/index.php?$args;
    }
    location /test/2/ {
        try_files $uri $uri/ /test/2/index.php?$args;
    }
    location ~ \.php$ {
        ...
}

在許多建議中,沒有一個有效。

普通 PHP 運作良好。 WordPress 和 Laravel 給出「找不到文件」:

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

文件未找到:

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

在以下所有嘗試中,它都會下載 PHP 檔案而不是運行 PHP:

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

server {
    server_name example.com;
    root   /var/www/example.com;
    location ~ /(.*)/ {
        try_files $uri $uri/ /$1/index.php?$args;
    }
    location ~ \.php$ {
        ...
}

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

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

如果可以的話,我願意為正確答案付出 10 美元

答案1

正規表示式區塊location是依序求值的,因此該.php區塊必須放在該/test/...區塊之前,否則.php下面的檔案/test/將被下載而不是被執行。看這個文件了解詳情。

你最好的版本是倒數第二個。正規表示式僅提取前綴後面的路徑元素/test/

只需顛倒location方塊即可。例如:

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

相關內容