Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to set up a redirect with PHP

This guide shows you how to send visitors from one web page to another using a few lines of PHP.

How-To Guides2 min read7 steps

What is a redirect?

A redirect is like a "we have moved" sign. A visitor goes to an old address, and the browser is sent to a new one on its own. You may want this when you rename a page, move to a new domain, or switch from http to https.

PHP is a language that runs on the server and powers many websites. It can tell the browser where to go next.

Types of redirect

  • 301: moved for good. Search engines move the old page's ranking to the new page. This is the most common choice.
  • 302: moved for now. Use this for short changes.

Steps

  1. Log in to your hosting control panel. The details are in your Hostvento welcome email.
  2. Open File Manager and go to your website folder, often public_html.
  3. Find the old page, for example old-page.php. Right-click it and choose Download to keep a backup.
  4. Right-click the file and choose Edit.
  5. Delete the old content, or leave it if you are sure the redirect runs first. Put this at the very top of the file:
<?php
header("Location: https://example.com/new-page.php", true, 301);
exit;
?>

The header line tells the browser the new address and that the move is permanent (301). The exit line stops the page from running any more code.

  1. Click Save Changes.
  2. Visit the old address in your browser. You should land on the new page.

Important rules

  • Put the redirect code before anything else. No HTML, no spaces and no blank lines before <?php.
  • If you see "headers already sent", something was sent to the browser before the redirect. Move the code higher up.
  • Always keep exit; after the header line.

Redirect with a condition

You can redirect only some visitors. For example, to force https:

<?php
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], true, 301);
    exit;
}
?>

This checks if the visit is not secure. If so, it sends the visitor to the https version of the same page.

Tip: Your browser remembers 301 redirects. If a test looks wrong, clear the cache or use a private window.
Tip: To redirect a whole site, a rule in the .htaccess file is often easier than PHP.

Quick recap

  • A redirect sends visitors from one address to another.
  • Use header("Location: ...", true, 301); followed by exit;.
  • 301 is permanent, 302 is temporary.
  • Put the code at the very top of the file.
  • Back up the file before you edit it.