A better rewrite?

 

Usually, while routing pages to various different scripts, and using a nice URL to hide all that, we take help of mod_rewrite a lot. For example, if we are have a user.php file with arguments name=indranil and want the URL to be domain.com/user/indranil, we  can use some very basic mod_rewrite to route user.php?name=indranil to /user/indranil.

However, not everyone is a mod_rewrite expert, and not ever server supports mod_rewrite.

There is, however, a much better, cleaner and more efficient way of handling routing. If, instead of using domain.com/user/indranil, we use domain.com/index.php/user/indranil, we will have a $_SERVER variable PATH_INFO which reads “/user/indranil”, all available for you to explode and use.

And then, if you want to remove the index.php part, just use this tiny bit of mod_rewrite

RewriteEngine on
RewriteCond $1 !^(index\.php|public)
RewriteRule ^(.*)$ index.php/$1 [L]

Now, every requests to domain.com/user/indranil will be available to the index.php file, which can easily parse the URL variable stored in $_SERVER['PATH_INFO'].

And even if mod_rewrite support is unavailable, you’ve got to agree that even domain.com/index.php/user/indranil is much better looking and SEO’d than domain.com/user.php?name=indranil.

Also, the URL variable is also available on $_SERVER['REQUEST_URI'] AND $_SERVER['PATH_INFO'].

 

Post a comment