Don't abuse PHP's header function for redirects

2 Comments

PHP's Header function can come in quite handy when you're building your next greate web application.  Its powerful, but as a result, its tempting to misuse it to do even the simplest things, like permanent redirects.  Usually, its done like this:


// redirect /publications (this page) to real page (/documents)
Header("Location: /documents/");

One line of code, time to move on to the next task in your queue, right?   No.  Why is this wrong or wasteful?  We're making the web server fire up the PHP processor to do something it can do more efficiently.  If we avoid using PHP, our request should be served faster and with less memory usage.  If you're on Apache, then the Rewrite module can do this for you, assuming your hosting provider has it enabled and allows you to control it via .htaccess files.  The better way to do this is with the following:


RewriteEngine On
RewriteRule /publications/?   /documents/   [R=permanent, L]

The "permanent" part is important, in that it'll trigger well-behaved spiders and user-agents, like Google, to update their link database and avoid the redirect in the future altogether.  If you have a lot of redirects, this solution excels for its maintainability as well.  Keeping them all in a single .htaccess file will save you from having to hunt through multiple PHP files for that header() call.

Nyk Cowham

You can also use the Redirect directives provided by mod_alias (which is almost universally enabled
on most web configurations). It's pretty simple to use: RedirectMatch permanent /publications/?
/documents/ Like the rewrite rule this will return a 303 status response to the client indicating a
permanent move. Either directive will get the job done efficiently. However, I still swear by the
good ol'fashioned HTTP-EQUiV refresh :D I'm sure we can come up with even better
inefficient approaches to solved problems if we try.

2007-09-01 9:45 pm

Ramiro

Do not forget to write "exit;" after the redirect to avoid weird behaviors.

2009-03-06 8:01 am