htaccess请求为'文件夹'

时间:2014-02-03 18:32:05

标签: php .htaccess mod-rewrite

我遇到了一个问题,我试图将网址映射到文件夹(虚拟网站), 所以,我试着而不是http://site.eu/controlpanel.php?username=Username&do=services 将其映射为http://site.eu/cp/user/services

我使用以下代码
RewriteRule ^cp/([^/]+)/([^/]+) /controlpanel.php?username=$1&do=$2 [L,QSA,NC]

一切都很好,除了两件事,如果我试图访问

http://site.eu/cp/user/

它给我404错误(为什么?)
此外,如果我试图访问除

以外的任何内容
http://site.eu/cp/user/services/

http://site.eu/cp/user/services/ServiceID/

http://site.eu/cp/user/services/ServiceID/Action

它给了我同样的错误。

在php文件中,我正在使用这种结构

<?php
switch($_REQUEST['do'])
{
   case 'services':
    some code to display page;
   break;

}
?>

在用户可以使用/ cp / user / services / ... / ...后,我不知道如何制作此页面。

请帮帮我

2 个答案:

答案 0 :(得分:1)

您需要使第二个参数可选,并且匹配多个路径节点:

 RewriteRule ^cp/([^/]+)/(?:(.+)|)$ /controlpanel.php?username=$1&do=$2 [L,QSA,NC]

答案 1 :(得分:1)

您可以使用以下结构:

RewriteRule ^cp/([^/]+)/?(.*)$ /controlpanel.php?username=$1&path=$2 [L,QSA,NC]

所以,如果你使用URL:

http://site.eu/cp/user/services/ServiceID/Action

...你会被发送到:

http://site.eu/controlpanel.php?username=user&path=services/ServiceID/Action

然后,在您的PHP文件中:

<?php
$path = ($_REQUEST['path']) ? explode('/', strtolower($_REQUEST['path'])) : array();

if (!empty($path)) { // A path is established; find the page.

    if ($path[0] === 'services') {
        if (!empty($path[1])) { // Visitor is at '/cp/user/services'.
            // ...
        }
        else if (ctype_digit($path[1])) { // Visitor is at '/cp/user/services/[ServiceId]'.
            // ...
        }
        // ...
    }

}
else { // No path exists. Visitor is at '/cp/user'.
    // ...
}
?>