Answered by
Oliver Hall
Implementing a 301 redirect in PHP is commonly used for URL redirection, particularly useful when you have moved a page permanently to a new location. A 301 redirect informs search engines and other users that the page has been moved permanently, helping preserve your SEO rankings.
To implement a 301 redirect in PHP, you can use the header()
function. This function allows you to send raw HTTP headers to the client. Here’s a simple example:
<?php // Permanent redirection header("HTTP/1.1 301 Moved Permanently"); header("Location: http://www.newdomain.com/newpage.html"); exit(); ?>
header("HTTP/1.1 301 Moved Permanently");
sets the HTTP status code to 301, which tells the browser and search engines that this is a permanent redirect.header("Location: http://www.newdomain.com/newpage.html");
specifies the new URL to which the user should be redirected.exit();
after sending headers to make sure no additional output is sent that could interfere with the redirection.header()
calls; otherwise, you'll encounter errors as headers cannot be modified once output has begun.ob_start()
and ob_end_flush()
) in your script, headers can still be sent even after some output has been generated.