Skip to Content

PHP 301 Redirects: Functionality & Best Practices

Creating a 301 permanent redirect in PHP is a common task, especially when you want to redirect users from one URL to another. A 301 redirect is useful for search engine optimization (SEO) as it informs search engines that the original URL has permanently moved to a new location.

Here's a step-by-step tutorial on how to create a 301 permanent redirect in PHP.

Ad - Web Hosting from SiteGround - Crafted for easy site management. Click to learn more.
Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

Code Examples

Absolute URL Redirects

In PHP, you can use the header() function to send a raw HTTP header to a client. In this case, we'll use it to send a 301 Moved Permanently header:

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

You can also use a shorthand method, passing in the HTTP status code of 301 for the redirect:

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

Make sure you replace the URL in the example with the URL you want to redirect to.

Relative URL Redirects

You can also redirect pages internally within your domain using relative URLs. 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 your 301 redirect in PHP, it's important that you specify 301 as your HTTP status code. If you omit it, PHP will automatically assume the status code of 302, which is a temporary redirect. In most cases, pages are moved to new locations to stay.
  • Make sure to put your 301 redirect high up in your PHP 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.
  • After sending the header, it's crucial to add the exit() function to ensure that no further code is executed. This prevents unexpected behavior and ensures a clean redirection.


By following these steps, you can easily create a 301 permanent redirect in PHP. Remember to replace the placeholder URLs with your actual source and destination URLs. Additionally, always test your redirects thoroughly to ensure they work as expected.

Posted by: Josh Rowe
Last Updated: December 06, 2023
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.