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.
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");
header("Location: https://orangeable.com");
exit();
You can also use a shorthand method, passing in the HTTP status code of 301 for the redirect:
header("Location: https://orangeable.com", true, 301);
exit();
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: /");
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 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.
Conclusion
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.
Comments
There are no comments yet. Start the conversation!