How to do PHP based 301 redirects
One common problem with script based redirects is that often they default to using 302 (moved temporarily) as response code. However, as the meaning moved temporarily already implies, that code is not meant for pointing to permanent locations like linked sites of a redirector script (for instance an outbound click tracker). In this case it would be more appropriate to tell both browsers and search engines that the endpoint of the redirect should be preferred over the link that caused the redirect. So how to get it done the correct way, when the stock location header sent by PHP defaults to code 302?
The answer lies in reading the PHP documentation thoroughly, especially the provided examples ;-). As long as no html output has been spilt (sometimes accidentally via whitespace as result of sloppy editing) you can send as much headers as you like. The documentation specifically mentions two cases:
There are two special-case header calls. The first is a header that starts with the string “HTTP/” (case is not significant), which will be used to figure out the HTTP status code to send.
[...]
The second special case is the “Location:” header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless some 3xx status code has already been set.
(emphasis mine)
There lies the answer: If we want to use a 301 redirect, we will have to send two headers:
<?php
header("HTTP/1.1 301");
header("Location: http://www.example.com/");
?>
which results in:
HTTP/1.1 301 Moved Permanently Date: Fri, 11 Apr 2008 21:22:56 GMT Server: Apache/1.3.34 (Unix) Location: http://www.example.com/ Content-Type: text/html
Exactly what we wanted.
Also, this response demonstrates that headers mentioned will replace similar ones and the rest will be accomplished by server defaults. Another usage of this “replace” feature could be to fool nasty bots with unexpected error codes like:
<?php
header("HTTP/1.1 402");
?>
Which yields in:
HTTP/1.1 402 Payment Required Date: Fri, 11 Apr 2008 21:29:57 GMT Server: Apache/1.3.34 (Unix) Content-Type: text/html
You may wish to add an error page with a credit card payment form to complete the confusion :-).
No Comments »
No comments yet.
RSS feed for comments on this post
Leave a comment
Posting comments requires Javascript to be turned on.