Question: How do you implement a 301 redirect in PHP?


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:"); exit(); ?>

Steps Explained:

  1. Set HTTP Status Code: The line 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.
  2. Set Location Header: The header("Location:"); specifies the new URL to which the user should be redirected.
  3. Exit Script: It's essential to call exit(); after sending headers to make sure no additional output is sent that could interfere with the redirection.

Things to Consider:

  • Ensure no output (like HTML or whitespace) precedes the header() calls; otherwise, you'll encounter errors as headers cannot be modified once output has begun.
  • If using output buffering (ob_start() and ob_end_flush()) in your script, headers can still be sent even after some output has been generated.
  • Always test redirects in various browsers and configurations to ensure they work as expected.

Other Common Website Redirects Questions (and Answers)

© ContentForest™ 2012 - 2024