PHP MVC with better htaccess

我的未来我决定 提交于 2019-12-08 06:36:23

You can try this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)(/([^/]+))?$ controller/$1.php?method=$2&param=$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.

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'

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!