首页 > 解决方案 > Nginx + PHP-FPM 重定向到静态 PHP 文件

问题描述

首先是关于我的设置的一些细节:

我有以下工作Nginx 配置:

upstream fastcgi_backend {
    server localhost:9000;
    keepalive 30;
}

server {
    listen   80;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;

        location ~ ^/(api|api-debug)/ {
            root       /app/webroot;
            index      index.php;
            try_files  $uri /api/index.php$is_args$args;

            location ~ \.php$ {
                fastcgi_pass   fastcgi_backend;

                fastcgi_split_path_info ^(?:\/api\/)(.+\.php)(.*)$;
                fastcgi_param  SCRIPT_FILENAME /app/webroot/$fastcgi_script_name;

                include        fastcgi_params;
            }
        }
    }
}

我只是想让它更简单、更高效,因为我现在看到它一团糟。例如,我试图调整

try_files $uri /api/index.php$is_args$args;

try_files $uri /api/webroot/index.php$is_args$args;

它失败了......它起作用的唯一原因是/api/index.php包含/api/webroot/index.php,但我认为它效率低下。

我发现调试 nginx 配置很困难,因为它不容易测试。

非常感谢您提前提供的帮助!

标签: phpnginxstaticfpm

解决方案


最简单的解决方案是将 SCRIPT_FILENAME 的值硬连线/app/webroot/index.php并完全删除您的一个location块。

location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
}

location ~ ^/(api|api-debug)/ {
    include        fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME /app/webroot/index.php;
    fastcgi_pass   fastcgi_backend;
}

或者,为了保持指定带有.php扩展名的 URI 的灵活性,您可以通过以下方式简化配置:

location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;

    rewrite ^/(api|api-debug)/ /index.php last;
}

location ~ \.php$ {
    include        fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME /app/webroot$uri;
    fastcgi_pass   fastcgi_backend;
}

推荐阅读