In this programming tutorial, we will look at different methods to redirect URLs in PHP. Specifically, we will be examining 301 URL redirect methods via code, meta refresh and the use of PHP header location settings to invoke a redirection.
So far the examples above will return a 302 as the header status. The most important redirects in real-world implementations use the 301 redirection status. The primary reason is that it is the only “search engine friendly” redirect. If you moved the URL to its new location, search engine ranking scores such as Google PageRank won't be passed to the new URL unless you are using 301 redirects.
The 301 is now included to make sure it will return a 301 header status. You can check this using Firebug if you are using a development server. Or if you are testing this using a live server, you might need to use a server header status checker such as: http://www.seoconsultants.com/tools/headers.
Common 301 redirection PHP code examples (always remember to place these codes above any HTML and ensure that HTML is not outputted first):
1.) Conditional 301 redirect (redirect when the URL matches to a given URL)
<?php
//Function to get the current URL of the website function currentpageurl() { $currentpageurl = 'http'; if ($_SERVER["HTTPS"] == "on") {$currentpageurl .= "s";} $currentpageurl .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $currentpageurlL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $currentpageurl .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $currentpageurl; }
//Equate the current URL with $currentpageurl variable $currentpageurl=currentpageurl();
//Redirect to the secure version header("Location: $secureversion",TRUE,301); exit(); }
echo "Hi, this will redirect any non-secure page to equivalent secure page"; ?>
Disclaimer and remarks: The above scripts are provided for illustration/basic example purposes only. In actual implementation, the above sample redirection scripts might be tweaked further to fully fit the implementation.