Check your web redirects and HTTP responses
Redirects in PHP
PHP sends HTTP headers using the header() function. It must be called before any output, including spaces or line breaks before the <?php tag.
Permanent 301 redirect in PHP
Place at the very top of the file:
Modern syntax (PHP 5.4+, recommended):
<?php
http_response_code(301);
header("Location: https://www.example.net/new-page.php");
exit();
?>
Alternative syntax (compatible with all PHP versions):
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.example.net/new-page.php");
exit();
?>
Temporary 302 redirect in PHP
By default, PHP sends a 302 code when you use header("Location: ..."):
<?php
header("Location: https://www.example.net/directory/page.php");
exit();
?>
To be explicit (recommended):
<?php
http_response_code(302);
header("Location: https://www.example.net/directory/page.php");
exit();
?>
Conditional redirect in PHP
Redirect based on browser language:
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if ($lang == 'en') {
header("Location: https://www.example.net/en/");
exit();
}
?>
Redirect while preserving GET parameters:
<?php
$params = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
http_response_code(301);
header("Location: https://www.example.net/new-page.php" . $params);
exit();
?>