PHP Redirect

From DreamHost
Jump to: navigation, search

If you're looking for a simple way to redirect an HTTP request, a PHP header redirect is perfect for this. It is especially useful for those looking to redirect requests to their main domain to another directory under that domain, such as directing requests for mysite.com to mysite.com/blog. True, this can be done through the use of an .htaccess redirect, but some may find this a bit easier to grasp. Here's what you do...

Creating a simple redirect in PHP

  1. Either create a new text file on your local computer or create one directly on your account via the shell (more information on creating files contained on that page).
    1. Name this file index.php
    2. If creating the file on your local system, be sure to upload it to the directory where you would like the redirect to happen. Should you just want to redirect mysite.com (and not a sub directory), place the file in the root folder for that domain (specified when setting up hosting in the control panel).
    3. If creating the file through the shell, create it within the root folder for the domain (specified when setting up hosting in the control panel).
  2. Within that file, add the following line of code:
    <?php header("Location: http://www.mysite.com/blog"); ?>

Remember to change the sample URL to be that of where you would like the site forwarded.

You'll then have a simple and quick redirection that you can use to seamlessly redirect a HTTP request to any URL.