This is about the right implementation of HTTP redirect using a PHP function, particularly SEO in mind.
目次
Example of redirection with PHP
Here’s the PHP code for the redirection first.
<?php // Redirect to the new URL. $url = 'http://www.example.com/'; header('Location: ' . $url, true , 301); // End php output. exit;
Point in the procedure
1Do not output any character before the header function
Any output in PHP will induce the HTTP header to send. So in order for the header function to work, you need to be careful so that there’s no output before it runs.
The header function fails if the HTTP header has already been sent out.
2Add the HTTP status code to the fourth argument
In any redirect, Google search engine look for the signal on “why this page is redirected”. There’s basically two options that you need to choose between when you implement redirection of a page.
Basically, the rule is:
- Use 301 when you want to redirect the page forever
- Use 302 when you temporarily move the page
Here’s a bit more detail.
301 (Moved permanently)
This is one you tell the search engine that the page is moved forever and that the search result should be the new URL.
302 (Found)
This is the major signal of the page is TEMPORARILY moved to another page.
There’s other HTTP codes that represents temporary move, but for historical reason, 302 is currently best way and Google also recommends using it.
If you know more about the HTTP status codes, the Wikipedia elaborates a lot about it.
3“exit;” at the end
This is not required and the redirect does work without this statement. However, if you want to be really safe, finishing PHP is recommended since it only takes one line (five letters!) in your PHP file.
The reason why putting exit at the end is:
- Some crawler (like Google search engine) might ignore the HTTP status code and get into the PHP file.
- If you want to guarantee the obsolete page is not on the internet anymore, just do not let it exist.
For a little more about this exit, this article should be helpful.
- http://thedailywtf.com/articles/WellIntentioned-Destruction
Summary
Another thing you should know is, you web browser also looks at the HTTP status code and behave differently depending on it.
For example, if it’s 302 meaning temporary move, you browser cache the file only during the session and doesn’t keep any longer whereas with 301, the cache is stored much longer.
Just a little bit of care about SEO will help you don’t mess up on the Internet world controlled by the search engine.
OK, that’s about it, take care.