How to Create a 301 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 in PHP with a 301 redirect.
A 301 redirect is an SEO-friendly and safe way of redirecting your users to a new desired location. 301 is the HTTP status code used to instruct your browser of the type of action needed.
The Code
As an example, we'll explore two different methods for redirecting our current page to https://orangeable.com using a 301 redirect in PHP. You can either do this with a few lines of code:
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://orangeable.com");
exit();
Or you can use the shorthand version:
header("Location: https://orangeable.com", true, 301);
exit();
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: /");
exit();
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 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 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.
- Make sure to always add
exit();
immediately after your 301 redirect. Doing so will ensure execution of the script stops and nothing further is processed.
Conclusion
This tutorial showed you how to properly create a 301 redirect in PHP.
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
Comments
There are no comments yet. Start the conversation!