A variation on one of the above from user2305090 which works for me:
First, add the following to your .htaccess file where /forwarding-site-nocase.php is my custom 404 page URL.
ErrorDocument 404 /forwarding-site-nocase.php
Then, at the very top of your custom 404 page, starting on line 1, add the following. If you have a blank line first, it fails.
<?php
$mydir=getdir("/",$_SERVER['REQUEST_URI']);
if($mydir!=false)
{
$thedomain = 'https://' . $_SERVER['SERVER_NAME'];
header("HTTP/1.1 301 Moved Permanently");
header( 'Location: ' . $thedomain.$mydir );
}
function getdir($loc,$tfile)
{
$startloc=$_SERVER['DOCUMENT_ROOT'];
if (file_exists($startloc.$loc) && $handle = opendir($startloc.$loc))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strncasecmp($loc.$file,$tfile,strlen($loc.$file))==0)
{
if(strncasecmp($loc.$file,$tfile,strlen($tfile))==0)
{
return $loc.$file;
}
else
{
return getdir($loc.$file."/",$tfile);
}
}
}
closedir($handle);
}
return false;
}
?>
Now you can follow this with your standard HTML for your custom 404 page such as:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Language" content="en" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Company information page - Page Not Found Error"/>
<meta name="search" content="Company information page - About Us. Manufacturer of rack mount rugged computer systems and rugged LCD displays for the military and industrial markets" />
and so forth for the rest of the page.
Note I changed the "http://" to "https://" and the error file explicitly to .php, since the original suggested version threw an error.