I want to implement a custom Error 400 page on my website tikolu.net
, to a file called 400.php
in a folder called error
.
The first thing I tried was to simply place ErrorDocument 400 /error/400.php
into my .htaccess
file. This doesn't work because for errors like 400, it cannot be handled by the .htaccess
file and instead must be placed into the httpd.conf
file, as mentioned here.
This works in the sense of being acknowledged by Apache, but it still does not fully work. The default message still displays, but this time with this added at the bottom: Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request.
This is because ErrorDocument
does not redirect, but instead just rewrites the URL, while now trying to show 400.php
. But because this is just a rewrite, Apache still thinks that the requested document was the same one which initially caused the error, so it results in an Error 400 again.
The furthest I managed to get is instead say ErrorDocument 400 https://tikolu.net/error/400.php
. This works because Apache cannot rewrite the URL again (as it is an external one), and is forced to redirect. However, this won't work for me as I need to know the original URL which caused the error. I tried getting $_SERVER["HTTP_REFERER"]
from PHP but it is empty.
The ErrorDocument
directive has access to some variables, like REDIRECT_URL
but they are only set if the target is internal, so it wouldn't work in this case.
Is there a possibility to use ErrorDocument
but with a proper redirect, so that it can be handled by a PHP script, without repeating the error? If not, is there a way to use the directive's variables when being redirected to an external location?
Here are the contents of my .htaccess
file:
RewriteEngine On
IndexOptions +Charset=UTF-8
# REMOVE www FROM URL
<If "%{HTTP_HOST} == 'www.tikolu.net'">
RedirectMatch (.*) https://tikolu.net$1
</If>
# REDIRECT HTTP TO HTTPS
<If "%{HTTPS} == 'off'">
RedirectMatch (.*) https://tikolu.net$1
</If>
# BLOCK .listing FILE
<Files ~ "\.listing$">
Require all denied
</Files>
# DIRECTORY INDEXES
DirectoryIndex index.php index.html
# ERROR DOCUMENTS
ErrorDocument 404 /error/404.php
ErrorDocument 403 /error/403.php
# REDIRECTS
(various redirects follow, all in the form RewriteRule location$ /destination [L]
)
I have disabled my .htaccess
file temporarily (by renaming it), and the problem still remains.
EDIT: I managed to find a slightly hacky (but working) workaround:
ErrorDocument 400 '<meta http-equiv="refresh" content="0; URL=/error/400.php">'