404 error redirect

greg's picture

He has: 1,581 posts

Joined: Nov 2005

I'm trying to redirect to a specific file on server return codes like 403, 404 etc.

In the root htaccess all error codes are returned to a file, I did have them redirecting to redirect_error.php that used header redirect to a root error.php page.

<?php
exit(header('Location: /error.php'));
?>

That worked fine, and if anyone was trying to get in a directory they shouldn't (403), or a directory or file that doesn't exist (404) or a server level password protected dir(403) they simply got redirected to the root and the error page.

But when I added Google's analytics it complained about my 404 being a 200 Doh!
Removing the redirect system I had resolved that issue, setting the root htaccess to go straight to the root error.php file.

What other methods are there or a way around Google's issue?
One of my dirs is pwd protected and when the popup occurs and they click cancel, they get the error page from the htaccess 403, but the password pops up again when the error page loads as the browser URL is still domain.com/pwd_protected_dir/

My redirect resolved this as it sent them to domain.com/error.php

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

is there a reason why you cannot just use the .htaccess directives:

ErrorDocument 404 /error.php
ErrorDocument 403 /error.php

In the error.php, are you feeding out a header to indicate the page is actually a 404?

-Greg

greg's picture

He has: 1,581 posts

Joined: Nov 2005

That is exactly what I do.

But previously I had it so the htaccess directives went to the redirect_error.php file, which that file then used the PHP exit(header) code to send it to error.php.
I did this as it reset any bad filenames or directories in the users address bar as they had new headers to an exact file location.

As Google analytics complained about the 403 being a 200 response and it wouldn't accept the analytic file until I rectified this issue, I had to change the htaccess directives to go straight to the error.php file and not the one that instigated the header redirect.

As such, you can type a non-existent directory in the address bar, and although the error page is loaded successfully from the htaccess directive, it doesn't change the URL. So domain.com/non-existent_dir/ remains as it is. And for directories password protected through plesk, the pop up login prompt keeps popping up for as the address bar remains the same and not redirected.

I.E. URL is still the password protected dir, and is now refreshed due to the error.php file being loaded and so the login pops up again due to reload.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.