问题
I have no idea how htaccess works, and the theory of it just wont connect in my head no matter how many tutorials I read.
I am building a simple MVC framework which works beautifully, except I don't like the way I am dealing with htaccess. To rewrite the URL's properly, this is what I am doing:
RewriteEngine on
RewriteRule ^users/([^/]+)(/([^/]+))?$ controller/users.php?method=$1¶m=$3
If I add a new controller, I then have to go into htaccess and add a new line:
RewriteRule ^access/([^/]+)(/([^/]+))?$ controller/access.php?method=$1¶m=$3
Is there a way to make it all automatic with wildcard fields so I don't have to access htaccess every time I do an update?
回答1:
You can try this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)(/([^/]+))?$ controller/$1.php?method=$2¶m=$4
The two extra rules will skip the rewrite if the file or directoy referenced actually exists on the disk, eg: it won't try to rewrite requests for http://site.com/images/logo.jpg
.
回答2:
You can move logic for parsing query string into your framework/application. For this, make you rewrite rule like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
In this case, any request to server will be processed by index.php (if static file with same name not exists). And $_SERVER['REQUEST_URI'] will be equal real request uri - just parse it and use for your logic.
For example, if send /user/registry request with that .htaccess
$_SERVER['REQUEST_URI'] => '/user/registry'
回答3:
I'd redirect all URIs to index.php
and allow another well established MVC concept handle the controller dispatching: Routers
.
Many (most) MVC (and some non-MVC) applications use this by default because it allows advanced routing techniques (not only controller/action structured URIs).
Controllers can "register" (new) routers and set their priorities. The application can run all routers (in order of priority) until one router finds a matching route (and is able to discern which controller should be used).
For example many blog-like applications will need SEO friendly URIs meaning something like category/subcategory/subsubcategory/blog-article.html
. Many cms-like applications will need the same for their hierarchical pages: top-level-page/mid-level-page/low-level-page.html
. As well as many eCommerce applications will want that for their products: category/subcategory/product.html
.
The above URIs need a router which will check the database to find out which article/page/product has that URI-key.
来源:https://stackoverflow.com/questions/16423258/php-mvc-with-better-htaccess