Skip to Content

How to Create a 301 Permanent Redirect with PHP

There may come a time when you move a page to a new location within your website, or switch domains entirely and need a way to navigate your users to your new domain. While moving things around can negatively affect your SEO (search engine optimization), there is a way to retain most of your ranking ability. Enter 301 permanent redirects.

A 301 permanent redirect is an SEO-friendly and safe way of redirecting your users to a new desired location. The 301 is the HTTP status code used to instruct your browser of the type of action needed.

Let's see how we can perform these redirects using some PHP code.

The Code

As an example, we'll explore two different methods for redirecting our current page to You can either do this with a few lines of code:

header("HTTP/1.1 301 Moved Permanently");

Or you can use the shorthand version:

header("Location:", true, 301);

Both code snippets perform the same action, so either can be used depending on your preference and style.

You can also redirect pages internally within your domain by omitting the domain name entirely. This example will send the user back to the home page:

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

A Few Important Tidbits

  • When creating permanent redirects, it's important that you specify 301 as your HTTP status code. If you omit this status code, PHP will automatically assume the status code of 302, which is a temporary redirect, something that should never be used for SEO purposes, in my opinion.
  • Make sure to put your redirects high up in your code, before any output is processed to the screen. This will ensure that your redirect will actually occur and that your script will not encounter any errors when processing the redirect.
  • When creating your redirects, make sure to always add exit(); immediately after your redirect. Doing so will ensure execution of the script stops and nothing further is processed.


It's a lot of information for such a simple task, but very important to cover so you can implement redirects properly within your applications.

Created: January 08, 2022


There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.