How to Redirect a Page with HTTP 301 in PHP

HTTP 301 Redirect is an SEO friendly way to redirect readers to a page’s new location. There are a lot of benefits of using HTTP 301 Redirect. These benefits can be found in the htaccess method post. htaccess or PHP can be both used for sending 301 redirects. The htaccess method can be found in How to Redirect Old Domain to New Domain Using htaccess Redirect. This post discusses the method that use php to generate the HTTP 301 Redirect.

As an example, we will redirect a page to https://www.systutorials.com in PHP.

The code:

<?php
// Permanent 301 redirection
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.systutorials.com/");
exit();
?>

Or simpler

<?php
header("Location: https://www.systutorials.com/", true, 301);
exit();
?>

The header(“HTTP/1.1 301”) part must be used before the location part, otherwise PHP will automatically set the status code to HTTP/1.1 302 Found.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

4 comments:

  1. is there a way to redirect a whole old domain to a new domain in php, including all the indexed urls? I have a HestiaCp setup, so if I modify the nginx.conf manually at every update it will be reset, and I can’t use the .htaccess file…

Leave a Reply

Your email address will not be published. Required fields are marked *