try_files 指令中的 nginx 多个 PHP 文件

nginx multiple PHP files in try_files instruction

早上好, 我想制作可以与不同 php 应用程序(symfony 和 Thelia)一起使用的相同 nginx vhost。 我的问题是 try_files 指令。在 symfony 中,try_files 必须以 app.php 为目标,但在 Thelia 中,它必须以 index.php 为目标。 所以我想修改try_files语句如下:

server {
    listen 80;
    server_name *.tld;

    root /var/www/web;

    location / {
        try_files $uri /app.php$is_args$args /index.php$is_args$args;
    }

    location ~ ^/(app|app_dev|config|index|index_dev)\.php(/|$) {
        fastcgi_pass php_alias:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param APP_ENV dev;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 256 16k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }

}

不幸的是,它不起作用。 Php 不再解释。那么如何在try_files语句中注册多个php文件呢?

try_files 指令只能有一个 默认 URI,它是最后一个元素,位于所有 文件 之后元素。您遇到的问题是 file 元素导致请求在当前 location 内处理。有关更多信息,请参阅 this document

您可以使用命名的 location 来处理可选的默认 URI,例如:

location / {
    try_files $uri @rewrite;
}
location @rewrite {
    if (-f $document_root/app.php ) {
        rewrite ^ /app.php last;
    }
    rewrite ^ /index.php last;
}

参见 this caution 关于 if 的使用。