简体   繁体   中英

Catch PHP 404 errors with nginx and fastcgi

I have set up a basic server for a client, and said client needs this to be based on nginx (I would normally use apache for PHP based servers)

This is the working config.

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

This works perfectly for most of the program. However I cannot catch PHP 404 errors, and this is needed for a module.

The module is in a directory called 'extra_app'

So I tried adding this inside the above config:

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

I need to be able to intercept 404 errors from php file requests in the /extra_app/ directory. I have added this to the .php section of the above config:

fastcgi_intercept_errors on;

This hasnt had any effect. (Yes, I restarted nginx service!)

Does anyone out there know of a solution?

Thanks!

[EDIT]

Im not sure if a 404 error page is needed... Maybe a 'mod_rewrite' rule can be written for nginx ? Im a newbie to nginx, im not even sure if you can rewrite urls...

One thing that might be causing you problem is the scoping of the location blocks. The error page directive is in one location block and php block that is being used when the error occurs is in another location block, so it doesn't see the error_page directive.

You can either move the error_page directive up a level (but then all 404 errors will be caught, or construct a copy of the php block but with the /extra-app prefix.

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

because nginx will chose the longest prefix, this will match in preference to the shorter one for all your other apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM