.htaccess ErrorDocument中的内容类型

jdg4fx2g  于 2023-01-17  发布在  其他
关注(0)|答案(2)|浏览(137)

我正在为我的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使用不同的Content-Type。text/plain或application/json都可以,但它们都不起作用。所以我可能无法像我想的那样在.htaccess中设置Content-Type头。我也尝试将ErrorDocument作为文件,但由于目录的路径是动态的,所以我无法使用没有硬编码路径的错误文档,如:

ErrorDocument 404 /api/index.php?error=404

htaccess在API目录里面,但是目录可以重命名,有没有什么方法可以实现下面的事情之一?

  • 在.htaccess中设置一个内容类型,这样ErrorDocument就不会包含带有字符集的text/html。
  • 将错误文档设置为.htaccess所在目录中的index.php。

如果第一个可以工作,我还能在.php脚本中覆盖它吗?我的一些调用是JSON,其他是XML文件。

svdrlsy4

svdrlsy41#

您可以使用ForceType指令执行此操作。
首先在DocumentRoot/folder/中创建一个名为error.json的文件,其中包含以下数据:

{"error":"API_NOT_FOUND"}

然后在您的DocumentRoot/folder/.htaccess中这样设置:

ErrorDocument 404 /folder/error.json
<Files "/folder/error.json">
   ForceType application/json
</Files>
5us2dqdw

5us2dqdw2#

谢谢你的答案,很抱歉这么晚才提供最终答案。我已经找到了一个解决方案,我认为它应该起作用。

<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没有被调用为clean时,我将输出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); }
}

相关问题