301 Redirects Using PHP

This method is helpful if you need to redirect on a small scale and using .htaccess or mod_rewrite are not an option. Old school META redirects can be SEO suicide. My situation when I needed to use this was when I was being hosted on an IIS server that did not allow URL rewriting. If anyone finds themselves in this position, hopefully this will be useful to you.

Create a file in your root directory called redirect.php that looks like the code posted below.


<?php

$redirect = false;
$path = $_SERVER['REQUEST_URI'];

if ($path == '/oldpath.php') {
    $path = '/newpath';
    $redirect = true;
}

$url = $_SERVER['HTTP_HOST'];
if ($url != 'www.yoursite.com') {
    $redirect = true;
}

if ($redirect==true){
    header('Status: 301 Moved Permanently');
    header('Location: http://www.yoursite.com'    .$path);
}

?>

For each URL you need to redirect from simply add another:


if ($path == '/oldpath.php') {
   $path = '/newpath';
   $redirect = true;
}

You could alternatively also use this to redirect from a www url to a non www version of your site by replacing the last two blocks with:


$url = $_SERVER['HTTP_HOST'];
if ($url != 'yoursite.com') {
   $redirect = true;
}

if ($redirect==true){
   header('HTTP/1.1 301 Moved Permanently');
   header('Location: http://yoursite.com' .$path);
}

And at the top of your default page (index.php) that you're using add the line:


<?php  require('redirect.php'); ?>

Again, the code posted "as is" is probably not the best solution if you are converting a large site as each url is listed individually, although if you are handy with regular expressions(which I am not), you might be able to tweak the code a bit to make it work for you.

Hi! I tried this

Hi! I tried this redirect.php on my drupal site. everything is ok, but it redirects only logged users it doesn't redirect anonymous visitors to specified pages. How can I do that? Thanx a lot! Max

301 for PR takes

Somebody use 301 redirect for takes the page's PR. burun estetiği

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

Verify Your Humanity
This question is for testing whether you are a human visitor and to prevent automated spam submissions.