301 redirections should be handled in the application, not .htacces

I see many tips and questions about how to redirect a URL with .htaccess rules. On the face of it, it makes a total sense, why should you waste the time to bootstrap  your website code (which might include DB access and what not), just to send a redirect response, when the webserver can do it much faster for you?

There are several reasons not to do it in .htaccess

  1. Unless you are redirecting most of the site, the rate of hits on a 301 should be low but the lines containing those roles in the .htaccess file still needs to be read and parsed for every url of the site, even those that serve javascript and CSS if you are using the naive approach in writting the rules. In contrast, your  application can check if a redirect is needed only after checking all other possibilities. Each check is slower but the accumulated CPU time spent on this will be lower. This of course depends on your rules and how fast your application determines that there is no match for a URL, and how likely a url is to require a redirect
  2. Statistics gathering. If you do it in .htaccess the only statistical tool you can employ to analyze the redirects is log file and they are rotating and bust a bitch to parse and collect into some better storage system.At the aplication you can simply write the data to a DB, or send an event to google analytics
  3. Your site should be managed from one console, and redirect are more related to a application level configuration then to webserver configuration. It can be very annoying if you write a new post, give it a nice url just to discover that for some reason it is always redirected to some other place without understanding why as your administration software do not know about the htaccess rule, and you probably forgot that it is there (or maybe even someone else put it there).

Leave a Reply

Your email address will not be published. Required fields are marked *