使用nginx和fastcgi捕获PHP 404错误


Catch PHP 404 errors with nginx and fastcgi

我已经为客户端设置了一个基本服务器,并表示客户端需要基于nginx(我通常会使用apache作为基于PHP的服务器)

这是工作配置。

server {
    listen 80;
    server_name localhost;
    auth_basic "My web site";
    auth_basic_user_file "/usr/local/nginx/www_passwd";
    location ~ ^/(?:share|conf) {
        deny all;
    }
    location ~ /'.ht {
        deny all;
    }
    location ~ /'.svn {
        deny all;
    }
    location / {
        root /var/www;
        index index.php index.html index.htm;
    }

    location ~ '.php$ {
        root "/var/www";
        fastcgi_pass unix:/etc/phpcgi/php-cgi.socket;
        fastcgi_index index.php;
        fastcgi_intercept_errors on;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

这对大多数程序来说都非常有效。然而,我无法捕捉PHP 404错误,这是模块所必需的。

模块位于名为"extra_app"的目录中

所以我试着在上面的配置中添加这个:

location ~ ^/extra_app/([a-zA-Z0-9'.])$ {
    error_page 404 = /var/www/extra_app/index.php;
    root /var/www/extra_app/;
    index index.php index.html index.htm;
}

我需要能够从/extra_app/目录中的php文件请求中截取404个错误。我已经将其添加到上述配置的.php部分:

fastcgi_intercept_errors on;

这没有任何效果。(是的,我重新启动了nginx服务!)

有人知道解决方案吗?

谢谢!

[编辑]

我不确定是否需要404错误页面。。。也许可以为nginx编写一个"mod_rewrite"规则?我是nginx的新手,我甚至不确定你是否可以重写url。。。

可能会给您带来问题的一件事是定位块的作用域。error page指令在一个位置块中,错误发生时使用的php块在另一个位置区块中,因此它看不到error_page指令。

您可以将error_page指令向上移动一个级别(但随后会捕获所有404个错误),也可以构造php块的副本,但带有/extra-app前缀。

   location ~ ^/extra_app/(.*'.php)$ {
        root "/var/www";
        error_page 404 /extra_app/404.php
        fastcgi_pass unix:/etc/phpcgi/php-cgi.socket;
        fastcgi_index index.php;
        fastcgi_intercept_errors on;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

因为nginx将选择最长的前缀,所以对于所有其他应用程序,这将优先于较短的前缀。