Nginx – Serve a custom 404 page generated by PHP

http-status-code-404nginxphp-fpm

Here is how my php-fpm config is:

location @site {
    fastcgi_pass   unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME $document_root/index.php;

    fastcgi_intercept_errors on;
    error_page 404 /404;
}

Because fastcgi_intercept_errors is enabled, when my PHP router returns a 404, Nginx will redirect to /404. Good.

But since /404 is generated by my PHP application, and my PHP application correctly sets a 404 response code, then Nginx will try to handle the error again! (which obviously ends in a loop)

Is there a solution to this?

Best Answer

nginx is doing this because you told it to.

    fastcgi_intercept_errors on;

This means that nginx will not serve error responses generated by PHP, but have nginx handle them instead. Thus you get into your endless loop.

To resolve the problem, remove this directive (it defaults to off) or set it explicity to off.