A PHP Header Redirect is a technique used by web developers to send a raw HTTP header to the user’s browser that instructs it to navigate to a different URL automatically. This is particularly useful to redirect users after actions like submitting forms, logging in, or moving pages, improving user experience and site navigation.
The PHP header() function is the core tool for performing this redirect. It sends a “Location” header to the browser with the URL to redirect to. This function must be called before any actual output is sent to the browser, such as HTML tags or echoed content, because HTTP headers need to be sent before the page content. Following the header() call with exit is recommended to immediately stop script execution, ensuring no further code runs or output is sent after the redirect.
Here are ready-to-use code examples demonstrating both absolute and relative URL redirection:
<?php // Absolute URL redirect header("Location: http://www.example.com/target-page.php"); exit; ?>
<?php // Relative URL redirect header("Location: /folder/anotherPage.php"); exit; ?>
HTTP status response codes accompany redirects and inform browsers and search engines about the nature of the redirect:
- 301 Moved Permanently: Indicates the resource has permanently moved to the new URL. This is for permanent changes as it helps preserve SEO value by passing link equity to the new page.
- 302 Found (Temporary Redirect): Indicates a temporary move. Use this when the original URL will reinstated later. Search engines typically don’t update their indexes for 302 redirects.
Best practices for PHP Header Redirects include:
- Prefer 301 redirects for permanent URL changes to maintain SEO benefits.
Avoid redirect chains and loops, which can degrade user experience and increase load times. - Update internal links to point directly to the new URLs rather than relying solely on redirects.
- Regularly monitor redirects for errors (like broken or misconfigured redirects) to preserve smooth navigation and SEO health.
This way, we can conclude that using header(“Location: URL”); exit; in PHP enables clean, efficient redirection. Combining it with proper HTTP status codes and output confirms a smooth user experience and SEO-friendly site management.