如何配置.htaccess以支持MVC


How to config .htaccess to support MVC?

我想编写PHP MVC web应用程序。

现在我正在尝试将任何键入的URL路由到index.php,所以我按照创建了一个.htaccess文件

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [R,L,NS]

但当我尝试键入任何URL时,它会将我路由到具有完整路径的URL键入->127.0.0.1/mvc/xxx/路由至->http://127.0.0.1/C:/Program%20Files/EasyPHP-12.0/apache/htdocs/mvc/index.php

如果没有完整路径(C:''Program%20Files/EasyPHP-12.0/apache/htdocs),我想我会得到我想要的。

请帮助解决这个问题。

谢谢大家。孔塔普。

我在Windows XP上使用EasyHP。

扩展Jalpesh Patel的答案:

你的.htaccess会将url路径传递给路由器或排序,例如url:

http://example.com/mvc/controller/action/action2:

RewriteEngine on
RewriteBase /mvc
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?request=$1 [L,QSA]

将发送到index.php?request=controller/action/action2

然后在索引中,它希望将此请求路由到脚本的一部分,该部分执行以下操作:

/*Split the parts of the request by / */
$request = (isset($_GET['request']) ? explode('/', $_GET['request']) : null);
//but most likely $request will be passed to your url layer
$request[0] = 'controller';
$request[1] = 'action';
$request[2] = 'action2';

一个示例URL:http://example.com/controller/action1/action2/action3

在.htaccess:中使用此规则

<IfModule mod_rewrite.c>    
RewriteEngine On
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteCond %{REQUEST_URI} !-l
RewriteRule ^([a-zA-Z_-]*)/?([a-zA-Z_-]*)?/?([a-zA-Z0-9_-]*)?/?([a-zA-Z0-9_-]*)$ index.php?controller=$1&action1=$2&action2=$3&action3=$4 [NC,L]

考虑在中间给一个单词加下划线如你所见的规则是如何添加的

检索这些值​​通过来所以得到恢复:

$controller = (isset($_GET['controller']) ? $_GET['controller'] : "IndexController";
$action1= (isset($_GET['action1']) ? $_GET['action1'] : "IndexAction";
$action2= (isset($_GET['action2']) ? $_GET['action2'] : "";
$action3= (isset($_GET['action3']) ? $_GET['action3'] : "";

在验证控制器类以及是否存在带有class_exists()、method_existss()的方法之后。

if( class_exists( $controller."Controller", false )) {
        $controller = $controller."Controller";
        $cont = new $controller(); 
        } 
        else {
        throw new Exception( "Class Controller ".$controller." not found in: "__LINE__ );           
        }

针对您的行动:$action1

if( method_exists( $cont, $action1 )  ) {                   
$cont->$action1();
   } 
else {
 $cont->indexAction();                   
//throw new Exception( "Not found Action: <b>$action</b> in the controller: <b>$controller</b>" );           
            }