I will give you a idea about the easy implementation of error page handling with Nginx.
1. Setting error handler
Error handler can be set with the error_page directive. More about this directive you can find here.
Do this in your server block but better use a generic file and include this in every virtual host server block. I use for this a file “vhost” with all such settings.
The handler or html files are placed in a separate folder outside the webs. You can use a folder inside your Nginx settings (I use here for example a “html” folder).
The location block is needed to pass the correct root and file to php fastcgi. In this example I use a file “fastcgi” with this mostly used lines:
fastcgi_pass unix:/tmp/fastcgi.socket; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params;
Here the part in the server block (or in your generic vhost file for including):
# error handler, codes can also be combined
error_page 401 /error.php?c=401;
error_page 403 /error.php?c=403;
error_page 404 /error.php?c=404;
error_page 500 /error.php?c=500;
error_page 502 503 504 /error.php?c=50x;
# serve error.php from /etc/nginx/html folder
location =/error.php {
root /etc/nginx/html;
include conf/fastcgi;
}
2. PHP file
The error.php file will be called with the URL encoded error-code, so its easy to grab this code in the PHP file from the superglobal $_GET array.
To map this error code to a message string, use a associative array and a function to return the string.
This is the part in the error.php file:
"Autorisierung erforderlich! - Authorization Required",
"403" => "Zugriff ist nicht erlaubt! - Access forbidden",
"404" => "Seite wurde nicht gefunden - Page not found",
"500" => "Interner Serverfehler - Internal Server Error",
"50x" => "Seite ist momentan nicht verfügbar. Bitte Anfrage später wiederholen.
-
The page is temporarily unavailable. Try again later.");
// get the error string
function errorString($error) {
global $_err;
foreach ($_err as $key => $val) {
if ($key == $error)
return $val;
}
return "Unknown Error";
}
isset($_GET['c']) or die("Unknown Error");
$error = $_GET['c'];
$str = errorString($error);
?>
Error <?=$error?>: <?=$str?>
You can format the error page as you like. But remember: the web root url will be the actual virtual host! Easiest way: use inline CSS. If this is not your preferred way, place the css file in a virtual host (eg. your default virtual host)


English
Deutsch


