views:

489

answers:

2

I'm studying how to do url rewriting in a LAMP framework. I began my research by studying wordpress code. I looked at wordpress's .htaccess and saw this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

I was surprised AND delighted! I was surprised because I didn't see any of those regular expression-like rules. I was delighted because I can delay learning how .htaccess files work (rushing for deadline), use the above script and parse the $_SERVER variable in PHP for url data.

So my question is, what are the advantages/disadvantages of managing url rewrites in the .htaccess file? And what are the advantages/disadvantages of managing url rewrites in the PHP code?

+3  A: 

Doing so in PHP will lead to the loading of, parsing of and execution of more PHP scripts/code. If you do go this way, don't get to the right page with external redirects. Remember that PHP scripts are essentially compiled every time they're hit (opcode caching notwithstanding).

mod_rewrite will be much more efficient at doing this. It will also force you to keep such rules fairly simple since mod_rewrite can only use regular expressions (and a few other things) whereas in PHP you could potentially do anything (like doing database lookups to find the right page, etc). Not good.

Regular expressions aren't hard. Usually it's just a case of:

RewriteRule ^account/orders/(\w+)$ /account/orders.php?type=$1 [L]

90%+ of my rewrite rules look like that. Pretty basic stuff.

cletus
thanks cletus. I tried your url rewrite rule and it's giving me unusual results. I posted a follow up question here: http://stackoverflow.com/questions/669161/whats-wrong-with-my-rewriterule
John
+3  A: 

ModRewrite: use when there are few different variations. If you have many regular expressions, the server will feel the load (my experience was with 30 complicated regular expressions). Also, this locks you in to Apache (or a different vendor which supports this). Advantage: it is very simple to implement. Disadvantage: vendor lock in, less flexibility.

PHP: use when you might switch vendors (I had instances when the development was done in Apache and the live system was running lighttpd). Also use if you want to provide custom URL rewriting (we used this with an admin configuration screen for allowing the customer to define his own URL rewriting rules). Advantage: higher flexibility and platform independence. Disadvantage: it can potentially use more system resources.

SorinV