当访问所有其他文件被拒绝时,如何dynamic地将所有HTTP错误代码发送到一个PHP文件?

我有以下情况,我正在开发一个API。 我将所有stream量重写为一个名为: route.php PHP脚本,使用mod_rewrite

 1: RewriteEngine On 2: RewriteCond %{REQUEST_FILENAME} -f [OR] 3: RewriteCond %{REQUEST_FILENAME} -d 4: RewriteRule ^.* route.php [L] 

其他文件不应该是可访问的,这就是为什么我只使用白名单来访问route.php 。 为此我使用这个:

 order allow,deny <FilesMatch "route\.php"> allow from all </FilesMatch> 

我想发送所有的1xx,2xx(200除外),4xx,如果可能的话5xx HTTP状态码给PHP脚本(假设error.php?code=404 ,显示该状态码的dynamic错误页面。我可能error.php不允许在FilesMatch部分中访问error.php

我在本文中描述了部分我想要的东西,但我无法实现或设法按照上述方式使其工作。

我的目的是为了显示一个JSON输出(dynamic地基于状态码),如{'statusCode':'404','status':'Not Found'}包括我使用的所有常见(安全)HTTP头。

这个问题没有得到太多的关注,我自己也回答了这个问题。 所以我的答案。 这是可能的以下方式。 任何改进是值得欢迎的

下面应该在.htaccess文件中:

 order allow,deny deny from all <FilesMatch "^route\.php$"> # replace 0.0.0.0 with IP that is allowed to access the Matched files allow from 0.0.0.0 </FilesMatch> ErrorDocument 400 /error.php?code=400 ErrorDocument 401 /error.php?code=401 ErrorDocument 403 /error.php?code=403 ErrorDocument 404 /error.php?code=404 ErrorDocument 500 /error.php?code=500 <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^route.php/(.*)$ index.php [L] </IfModule> <IfModule !mod_rewrite.c> ErrorDocument 403 /error.php?code=403 </IfModule> 

以下应该在error.php文件中:

 if (!function_exists('http_response_code_text')) { function http_response_code_text($code = 403) { $text = 'Forbidden'; switch ($code) { case 400: $text = 'Bad Request'; break; case 401: $text = 'Unauthorized'; break; case 403: $text = 'Forbidden'; break; case 404: $text = 'Not Found'; break; case 500: $text = 'Internal Server Error'; break; default: $text = 'Forbidden'; break; } return $text; } } $code = 403; if(isset($_GET['code']{0})) { $code = (int) $_GET['code']; } $text = http_response_code_text($code); echo json_encode(array('httpStatusCode' => $code, 'httpStatusText' => $text)); 

这似乎并不适用于所有的HTTP错误代码,如414“Request-URI太长”,总是回退到403 Forbidden。