Don't abuse PHP's header function for redirects

Posted on Tuesday, Aug 28, 2007 at 11:58 PM in ,

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.

Comments

Nyk Cowham says

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.
Posted Sunday, Sep 2, 2007 at 01:45 AM

Post your comment

Required but will not be shown
URL for your own blog or site - begin with http or https.
Most HTML is allowed.
The values you submit will be saved to a cookie to automatically fill in this form.
 Yes, save it.

Meta

Links Out

Links In

View blog reactions

Technorati Tags

Feed

License

Subscribe via Email

Enter your email address:

Delivered by FeedBurner