Neil Turner's Blog

Blogging about technology and randomness since 2002

Permanent redirects in PHP

This is mostly for my own benefit but if you need to have a PHP script create a permanent (301) redirect, here’s how to do it:

header($_SERVER['SERVER_PROTOCOL'] . " 301 Moved Permanently");

I had some pages on Smaller World whose URLs changed some time ago that I’d forgotten to put redirects in for. Since I’m useless at regular expressions (despite owning O’Reilly’s Regular Expressions Pocket Reference book) I instead butchered the code for Movable Type’s dynamic publishing and added some redirect code for the pages in question. Since the URLs have now changed permanently I wanted to send the correct status code and this seems to be the way to do it.


  1. Nice trick. Why use PHP when you can use mod_rewrite? A mod rewrite flag of R=301 would do the same in a lot less code.

  2. It would be less code, and also faster and more efficient. However, I wanted the redirect to be conditional (only redirect if the filename follows a certain pattern) and the resultant page differed depending on the requested page. Again, that would be doable in mod_rewrite but I’m not that good with regular expressions so I used a PHP script instead.

  3. Acksherley, php’s header() statement has extra parameters to set response codes; without this, the header(“Location:…”) will return a 302 (see the php header() manual page).
    So, your first statement should be:

    header($_SERVER[‘SERVER_PROTOCOL’] . ” 301 Moved Permanently”, TRUE, 301 );