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” :
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.example.com");
die();

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:
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = $_SERVER["REQUEST_URI"];
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://'.$host.$uri);
die();

Source (contains examples in other programming languages, notably in Perl and using only mod_rewrite): http://www.somacon.com/p145.php

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.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA