Skip to content

HTTP 301 (permanent) redirect in PHP

A short one in the original spirit of this notepad, ie “I really don’t want to lose this ever again” :
header("HTTP/1.1 301 Moved Permanently");

For some reason I’ve always had a hard time setting this kind of headers in PHP. Now that I have the solution it just seems so trivial… 301 (permanent) redirects are an important thing to have when you’re changing the structure of your site’s URLs, this way search engines should be able to transfer your former URLs to your new ones. If you just do a 302 (temporary) redirect, they (most likely) won’t, or at least you might lose more pagerank than you should.

And here’s a more complete script if you want to redirect all your URLs to rewritten URLs instead of just a single same page:
$host = $_SERVER['HTTP_HOST'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://'.$host.$uri);

Source (contains examples in other programming languages, notably in Perl and using only mod_rewrite):

Posted in web development.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA