Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content-Type in ErrorDocument

I am building a small framework for my API's since they are quite specific, but I have a problem with the Content-Type when I received data for an ErrorDocument. Currently, I have the following .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>

What I want to achieve is the error 404 with a different Content-Type. Either text/plain or application/json would be fine, but none of those works. So probably I can't set the Content-Type header in the .htaccess like I want to. I also tried the ErrorDocument as a file, but since the path to the directory is dynamic, I can't use an error document without the path hardcoded like:

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

The .htaccess is inside the api directory, but the directory can be renamed. Is there any way I can achieve one of the following things?

  • Set a Content-Type inside the .htaccess so the ErrorDocument doesn't have the text/html with a charset.
  • Set the error document to index.php in the directory the .htaccess is.

If the first one works, would I still be able to override it inside the .php scripts? Some of my calls are JSON, other are XML files.

like image 469
Sietse Avatar asked Oct 14 '25 17:10

Sietse


1 Answers

You can use ForceType directive for this.

First create a file called error.json inside your DocumentRoot/folder/ with this data:

{"error":"API_NOT_FOUND"}

Then in your DocumentRoot/folder/.htaccess have it like this:

ErrorDocument 404 /folder/error.json
<Files "/folder/error.json">
   ForceType application/json
</Files>
like image 138
anubhava Avatar answered Oct 18 '25 07:10

anubhava