Reputation: 121
i am trying to build a mvc like application and i cant figure out the right .htaccess i need.
I want something like:
RewriteRule ^(.*)/(.*)/(.*)$ $1.php?action=$2&n=$3 [L]
so i can access the file that contains the proper controller and two get variables from the url. The code above doesnt work, i have been around this for 2 days now and i cant find anything like what i need anywhere.What happens there is that the 3 variables are required at the url in order to work, and thats not what i want. Sugestions?
Upvotes: 2
Views: 2112
Reputation: 22337
use this:
RewriteRule ^([^\./]*)$ index.php?route=$1 [L,NC,QSA]
then
$route = explode('/', $_GET['route']);
$id = array_pop();
$controller = array_shift($route);
$method = implode('_', $route);
$controller = new $controller;
$controller->$method();
Upvotes: 2
Reputation: 73031
Most frameworks use a Front-Controller instead of mod_rewrite
. This controller splits apart the URL and routes accordingly.
While not the only solution, this is more flexible. Consider when you have the URL plugin/controller/view/id
or controller/view/param1/param2
.
If you want to adopt the Front-Controller architecture, I'd recommend using FallbackResource
to keep your htaccess file trim.
FallbackResource /front-controller.php
From there it should be fairly straightforward to split apart the url with functions like parse_url()
.
Upvotes: 3