Forum Moderators: phranque

Message Too Old, No Replies

404 redirect does not work (mod rewrite and PHP)

         

crimsontwo

12:58 am on Dec 5, 2009 (gmt 0)

10+ Year Member



Re,

my .htaccess has the following entry:

RewriteRule ^catalog/([^/]+)/([0-9]+)/([0-9]+)/$ products.php?category=$1&page=$2&per_page=$3 [QSA,L]

my PHP script has the following code:

header("HTTP/1.1 404 Not Found"); exit();

for some reason the request is not further redirected from PHP to a generic Apache's 404 page, the same that appears if I type some nonsensical URL.

header('Location: '.getenv('HTTP_HOST').'/custom_404.php', true, 404); exit(); << doesn't work either.

however... header('Location: 'www.google.ca', true, 301); exit(); << works.

what am I doing wrong? why wouldn't it redirect to a 404 page (either Apache's default or my custom one)?

thanks!

jdMorgan

5:55 am on Dec 5, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Because after rewriting a client request to your products.php page, it is "too late" for Apache to "take back control" to handle the error -- The URL-to-filepath translation and fixup phases of the API are completed, and the content-handling phase has begun; Because the URI "products.php" is valid, there is no 404 as far as Apache is concerned... The status code you're outputting in your PHP code is sent to the client, not to Apache.

Once Apache passes control to your script, your script is fully responsible for the remainder of the content-handling phase.

Your PHP code should output the 404 status header (as you show above), and then it should "include" (e.g. using the PHP "require" directive) the contents of your custom_404.php error page.

You certainly *Do Not* want to 301/302 redirect to your error page -- In SEO terms, this is known as "suicide" because it will very likely damage your search rankings, and open your site up to at least one unpleasant competitor exploits...

Server config code and scripting have side effects extending to search engine rankings. Be careful, and especially never send a status response that does not comply with the HTTP protocol specification for that response.

Jim

g1smd

6:48 pm on Dec 5, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The above is exactly what you need to do.

Once the script has sent a 404 header it then needs to directly send the error message page content itself.