301 redirect with PHP301 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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus