Skip to content
Related Articles

Related Articles

How to add 301 redirects in PHP ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 09 May, 2022

In this article, we are going to discuss how to add 301 redirects in PHP. Sometimes we come across scenarios like a few web pages redirecting from one page to another page without clicking/doing anything. This can be done by developers if they want users to use their updated version of their webpage rather than the older version. PHP provides an easy and flexible way to redirect from one page to another page by specifying the new PHP file in the header method in an old PHP file. So using the header method we can add 301 redirects in PHP.

Header Function: Header function is an inbuilt function in PHP that sends a raw HTTP header to the client. This header function must be called before any output is sent because they manipulate the information sent to the client. Let’s look into the syntax of the header function:


header(header, replace, http_response_code)


  • header- It is the string to send. It is a required parameter in header function.
  • replace- Indicates the whether previous headers are replaced with new headers. Default value is True if not specified. It’s an optional parameter.
  • http_response_code- Forces the http_response_code to a specified value. It’s also an optional parameter.

Returns None.

Let’s look into the steps to add 301 directs in PHP


  1. The older source code file should be of the type PHP.
  2. Create a new source code file of type PHP to which it redirects. 
  3. Add redirect code by specifying the new PHP file name in the header method in the older source code file.

Add the below mentioned source code in the old PHP file to add redirection.

header(“Location:”, true, 301);

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

Example: Here we will be having two source code files one with an older version of the code and another source code file that has a newer version code to which it redirects when the user runs the old source code file. Below is the redirected newFile.php source code file.


  echo "New Version"

The below source code oldFile.php had the code that redirects to the newFile.php 


  header("HTTP/1.1 301 Moved Permanently"); 
  header("Connection: close");


This will change the location of the header, i.e. redirects 
to specified newFile.php and executes the code in it.
New Version

By using the oldFile.php source code file, Users will be redirected to and HTTP Status code 301 Moved Permanently is returned.

Note: If the header(“HTTP/1/1 301”) is not used then the HTTP status code is set to 302.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!