301 redirect with PHP
Posted March 15th, 2008 in PHP
When you change the URL/URI of a page, a permanent redirection should be set up from the old address to the new address to let user-agents know where it can now be found. When using a web browser the redirection is usually seamless; for search engine bots they will now know to stop requesting the old page and instead request the new address in the future. This post looks at how to do this with PHP.
In PHP it's very simple to do a 301 redirect. The example below shows how to do this by sending the new location as the website's homepage, using the $_SERVER['HTTP_HOST'] variable to set the domain name.
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://$_SERVER[HTTP_HOST]/");
Depending on what your script is doing, you may also need to add an "exit;" line underneath the code above to prevent it doing anything else.
If you need to redirect to a specific page, you can add it after the hostname part:
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://$_SERVER[HTTP_HOST]/path/to/my/script");
Although you are supposed to include the full URI, including the http:// and domain name part, it is possible to omit these and the user-agent will still follow through to the new address. For example:
header("HTTP/1.1 301 Moved Permanently");
header("Location: /path/to/my/script");
However you should really include the domain name to follow the specification.
Related posts:
- Setting 503 Service Temporarily Unavailable headers with Apache .htaccess (Sunday, March 14th 2010)
- 410 "Gone" with PHP (Thursday, September 3rd 2009)
- Set the content encoding type with PHP headers (Saturday, December 13th 2008)
- 404 Page not found with PHP (Wednesday, October 29th 2008)
- 303 redirect with PHP (Thursday, July 31st 2008)
- Image headers with PHP (Tuesday, July 22nd 2008)

Comments
blog comments powered by Disqus