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

相关内容