PHP 301 and 302 redirect

Let’s see how to do a redirect with PHP using the header() function. With redirect types 301, permanent, and 302, temporary.

A redirect is used to take the user’s browser to a different page. Redirecting the browser can help us to send it to a different URL where the content you want to see is located.

There are two types of redirects, 301 which means “Permanent Redirect” and 302 which means “Temporary Redirect”. The user who visits us does not perceive if we are doing a redirection of one type or another by PHP, but the type of redirection used is interesting information for search engines, because they will understand that an address has changed temporarily or permanently and that will help them to have updated their databases. This is explained in the FAQ: .

With PHP we can redirect the browser with the header() function, which sends information in the HTTP header.

A PHP redirect would look something like this:

header(“Location: http://www.a-redirection-anyone.com”);

By default, PHP performs a temporary redirection, type 302. But we can indicate another type of redirection, also with the header() function, indicating the type before doing the Location.

To do a 301 (permanent) redirect, we will use a PHP code like this:

header(“HTTP/1.1 301 Moved Permanently”);

header(“Location: new_page.html”);

To make a 302 redirect with PHP (temporary) the code would be like this:

header(“HTTP/1.1 302 Moved Temporarily”);

header(“Location: new_page.html”);

Remember then that it is good for search engines that a temporary redirection, type 302, at some point we change it for a permanent type (301), if the contents that have been moved will always maintain that location.

Loading Facebook Comments ...
Loading Disqus Comments ...