To forward http://www.site.com to site.com:
Code:
<?php
if(stristr($_SERVER["HTTP_HOST"], 'www')){
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://site.com/" . $_SERVER["REQUEST_URI"]);
die();
}
?>
To forward site.com to
http://www.site.com, use the following code:
Code:
<?php
if(!stristr($_SERVER["HTTP_HOST"], 'www')){
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.site.com/" . $_SERVER["REQUEST_URI"]);
exit();
}
?>
* Notice how we send the HTTP 301 header and then we immediately follow it with the new location.
* Also, notice that we forward the REQUEST_URI value. The REQUEST_URI is the path within the website to the web page. For example, in
http://ekstreme.com/phpcounter/index.php, the /phpcounter/index.php part is the REQUEST_URI. Our forwarding code above forwards to the user to the page they requested.
* Notice the exit() statement: this makes sure that the PHP code following this code does not get executed and that only the forwarding information is sent to the browser.
This code is best used for single pages that require forwarding, and not whole websites. To use it, just add the code at the very beginning of the page's PHP file. Make sure there are no spaces or any other characters before the opening <?php, otherwise, the code won't work and you'll get a warning.