Home > Software design >  Can't serve php custom error files from a parent folder in nginx
Can't serve php custom error files from a parent folder in nginx

Time:12-14

I have the following directory scheme

/srv/www/htdocs/www/

where www is the public directory root, and htdocs contains files outside the public access. This is the nginx.conf

server {
    listen       443 ssl http2;

    root   /srv/www/htdocs/www;

    location / {
        index index.php;
    }

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
        include fastcgi_params;
    }

    error_page 401 @errorPage;
    error_page 403 @errorPage;
    error_page 404 @errorPage;
    location @errorPage {
        root /srv/www/htdocs;
        rewrite ^ error.php?error=$status last;
    }

}

What I'm trying to do is to serve the error.php page when 401,403 and 404 triggers, but still I'm getting the default Nginx 404 page, even when I programmatically trigger 403 or 401.

Am I doing something wrong in the named location?

CodePudding user response:

Placing root in @errorPage is pointless. The location is a stepping stone to error.php which ends up back in the location ~ \.php$ with a root value of /srv/www/htdocs/www.

The simplest solution is to move error.php into the www directory.


If you want to keep error.php out of the www directory, you will need to replicate much of the location ~ \.php$ block within the location @errorPage block.

For example:

location @errorPage {
    fastcgi_pass  127.0.0.1:9000;
    include       fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /srv/www/htdocs/error.php;
    fastcgi_param QUERY_STRING error=$status;
}

Place the fastcgi_param statements after the include, otherwise the latter will override the new values.

  • Related