Difference between .htaccess and router


Can someone please explain me how is the working of an .htaccess file different from that of a router of an MVC framework?

I think they both handle the incoming request and if that is so why use both and not any of one of them?


The simplest answer is that most MVC frameworks strive to be portable. By relying on .htaccess you lose that as they wont run on IIS servers.

There’s a maintainability aspect as well. When initiating an MVC triad you need to select a model, a view and a controller. Although you can do this in .htaccess by passing three different variables to the entry point, you have to add a rule for each possible page, you can’t rely on a convention over configuration approach. Doing things in PHP simply gives you more power because it supports more complex logic.

.htaccess is often use alongside a router to simply make the URIs nicer.

But isnt it true that without the .htaccess the routers wont work?

If the framework is well designed it should work whether URL rewriting is available or not.

the rewriterule should be set up like this:

RewriteRule ^(.*)$ index.php?route=$1

The full route is then passed to the router. Most frameworks provide an inbuilt URL generating function which will create a URL based on whether rewrite rules are enabled or not.

For example, if they’re not, links will be generated to “index.php?route=/blog/123” whereas with a config option telling them URL rewriting is enabled, they’d generate “/blog/123”.

htaccess rules can be quit limiting and/or repetitive. Routing server-side in combination with htaccess offers much more control when it comes to matching URLs with complex rules/requirements.

AFAIK all major framework (Zend, cakephp) are dependent on mod rewrites. so i thnk they are interdependent.