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:
- Apache does not log HTTP status set with PHP header when using mod_rewrite in .htaccess files (Sunday, April 5th 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)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
