I did it! 301 Redirect via PHP! #News
Voodooman's hideout
Site news
20 Aug 2011 00:38
I did it! 301 Redirect via PHP!
Stupid third party site scripts consider www.domain.com/blahblah and domain.com/blah/ or domain.com/blah/index.php as different urls, this messing everything when users uses different links of same location.
So i need to set 301 redirects to unify all various types of urls as one. This isnt such a big problem, but in addition to this, but one of damn servers i use hot apache-powered, as result it is not familiar with .htaccess files and have pretty poor web-base interface for settings.
So i have no other option but to code 301 redirects via PHP.
This was challenging, because i never was a PHP gure and last time i coded something with PHP was almost year ago, so i already forgot everything about it and had to start from beginning - from lame docs on various sites. And this was pain in brain, because PHP is very server-dependable, and this bloody mess not works as expected. But after all i did it!
Now my domain always redirects to www mirror and /index.php files of every directory redirects to root of directory /, in same time user query and protocol remains preserved laughing.
Sounds simple, but coding this in PHP was not that simple, i spent half of day on this!
Well its not very optimized yet, im going to shorten it a little and i think i must use if\else more effective than this, but maybe current source would be useful for you:

$baseHost = 'www.domain.com';
$host = $_SERVER['HTTP_HOST'];
$file = $_SERVER['SCRIPT_FILENAME'];
$dir = dirname($file);
$request = explode('?',$_SERVER['REQUEST_URI']);
if(isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != ''){
$query = '?'.$_SERVER['QUERY_STRING'];
}
else{
$query = '';
}
if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443'){
$protocol = 'https';
}
else{
$protocol = 'http';
}
$prefix = $protocol.'://';
$suffix = 'www.';
if(strcmp($host,$baseHost) != 0){
$link = $prefix.$suffix.$host.$dir.$query;
header("HTTP/1.1 301 Moved Permanently");
header("Location: $link");
}
elseif(strcmp(basename($dir),basename($request[0])) != 0){
$link = $prefix.$host.$dir.$query;
header("HTTP/1.1 301 Moved Permanently");
header("Location: $link");
}
| More