PHP Redirect Guide (301 & 302 Header Redirection)

A comprehensive developer guide on server-side redirection in PHP using header('Location: ...'), status codes 301 and 302, and buffer handling.

Server-Side Redirection in PHP

In PHP, redirects are initiated by sending raw HTTP response headers using the built-in header() function before any HTML output, spaces, or text are sent to the client browser.

1. Permanent 301 Redirect (SEO Friendly)

Always specify the HTTP response code 301 when permanently moving a page, and follow immediately with exit() to stop script execution:

<?php // Permanent 301 Redirect header("Location: https://www.rapidtables.online/web-design.html", true, 301); exit(); ?>

2. Temporary 302 / 307 Redirect

For temporary maintenance, user login redirects, or conditional testing:

<?php // Temporary 302 Redirect (default in PHP) header("Location: /maintenance.html"); exit(); ?>

Fixing "Headers Already Sent" Warning

If you encounter Warning: Cannot modify header information - headers already sent, it means data was sent to the browser before the header() call. Common causes and fixes:

  • Ensure there are no whitespace or blank lines before the opening <?php tag.
  • Ensure the PHP file is saved with UTF-8 encoding without BOM (Byte Order Mark).
  • Enable output buffering at the top of your script using ob_start();.