我正在为我的API构建一个很小的框架,因为它们非常具体,但是当我收到ErrorDocument的数据时,我遇到了内容类型的问题。目前,我有以下.htaccess:
<IfModule mod_headers.c>
Header set Content-Type "text/plain"
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteRule ^([a-z]+)(/[A-Za-z0-9-\._\/]*)?$ $1.php [QSA,L]
ErrorDocument 404 "API_NOT_FOUND"
</IfModule>我想要实现的是带有不同内容类型的错误404。无论是文本/纯文本还是应用程序/json都是可以的,但所有这些工作都没有。因此,我可能无法像我想的那样在.htaccess中设置Content标题。我也尝试将ErrorDocument作为一个文件,但是由于目录的路径是动态的,所以如果没有硬编码的路径,就不能使用错误文档,如:
ErrorDocument 404 /api/index.php?error=404.htaccess位于api目录内,但可以重命名该目录。有什么方法可以让我达到以下目标之一吗?
如果第一个可以工作,我还能在.php脚本中重写它吗?我的一些调用是JSON,另一些是XML文件。
发布于 2016-04-21 13:24:56
谢谢你的回答,很抱歉这么晚才给出最后的答案。我已经找到了一个解决方案,我认为这是应该的。
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteRule ^([A-Za-z0-9_-]+)(/[A-Za-z0-9-\._\/]*)?$ $1.php [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^([a-z]+) index.php?error=404 [L]
</IfModule>错误被重定向到index.php,它在日志记录本身之后输出正确的内容,所以我相信这是一种双赢的情况。对于简单的解释,将在index.php中执行以下行:
http_response_code(404);
die(json_encode(['error' => ['code' => 'API_SCRIPT_NOT_FOUND', 'number' => 404]]);编辑:我将解释我所做的多件事。index.php通常会生成一个文档,但是当index.php没有被调用时,我将输出notfound错误。看起来是这样的:
<?php
class Documentation {}
$API = new Documentation();
require_once('common/initialize.php');
Output::notfound('API_SCRIPT_NOT_FOUND');
?>输出类是一个小类,它用正确的内容类型处理输出。当没有设置其他内容类型时,它会自动设置'application/json‘。一个小例子(有更多的函数,但这是它运行的函数):
class Output {
protected static $instance = null;
public static function instance() {
return self::$instance ?: self::$instance = new static;
}
private $finished = false;
private function finish($output, $status = null) {
if($this->finished) return; $this->finished = true;
http_response_code($status ?: 200); $content = null;
$headers = headers_list();
foreach($headers as $header) {
if(substr($header, 0, 13) == 'Content-Type:') {
$content = substr($header, 14); break;
}
}
if(!$content && !headers_sent()) {
header(sprintf('Content-Type: %s', $content = 'application/json'));
die(json_encode((http_response_code() >= 400) ? ['error' => $output] : $output));
}
die(!empty($output['code']) ? $output['code'] : $output);
}
public static function notfound($output) { self::instance()->finish(['code' => $output, 'number' => 404], 404); }
}发布于 2016-01-01 10:12:29
为此,您可以使用ForceType指令。
首先,使用以下数据在您的error.json中创建一个名为DocumentRoot/folder/的文件:
{"error":"API_NOT_FOUND"}然后在您的DocumentRoot/folder/.htaccess中这样做:
ErrorDocument 404 /folder/error.json
<Files "/folder/error.json">
ForceType application/json
</Files>https://stackoverflow.com/questions/34527333
复制相似问题