Home / 301 redirect with PHP

301 redirect with 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.