htaccess中的友好URL

时间:2014-11-26 22:09:55

标签: php apache .htaccess mod-rewrite

我在.htaccess中遇到友好网址的问题。 我需要这样的东西

http://example.com/cnt1/cmp1/act1/id,1/cid,2/sid,3/etc..
http://example.com/index.php?controller=cnt1&component=cmp1&action=act1&data=id,1/cid,2/sid,3/etc..

http://example.com/cnt1/cmp1/act1
http://example.com/index.php?controller=cnt1&component=cmp1&action=act1

http://example.com/cnt1/cmp1
http://example.com/index.php?controller=cnt1&component=cmp1

http://example.com/cnt1
http://example.com/index.php?controller=cnt1

http://example.com/
http://example.com/index.php

我的.htaccess文件:

Options +FollowSymLinks
RewriteEngine on

RewriteCond ${REQUEST_URI} ^.+$
RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|png|js|css|swf|ico|txt|pdf|xml|zip)$ [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteCond %{REQUEST_URI} !-l
RewriteRule ^([,a-zA-Z0-9_-]*)/?([a-zA-Z0-9_-]*)?/?([a-zA-Z0-9_-]*)?/?([/\.,a-zA-Z0-9_-]*)$ index.php?controller=$1&component=$2&action=$3&data=$4 [NC,L]

ErrorDocument 404 /index.php?controller=error404 

但有些问题,例如http://example.com/&http://example.com/<找不到错误。 有人能帮我吗?

1 个答案:

答案 0 :(得分:0)

我认为您可以通过使用更简单的网址重写规则轻松地在PHP中解析您的网址。

RewriteRule    ^(.*)$    /index.php?query=$1    [END,QSA]

在你的PHP中就像

// Parse Query
$default = [
    "defaultController",
    "defaultComponent",
    "defaultAction",
];
$query = explode('/', $_GET['query']);
$temp = array_slice($query, 3);
$query = array_merge($default, array_slice($query, 0, 3));

// Parse Data
if(!empty($temp)) {
    $data = [];
    $m = count($temp);
    for($i=0;$i<$m;++$i) {
        list($k,$v) = explode(',', $temp[$i]);
        $data[$k] = $v;
    }
}
else $data = null;

// Some testing
if(controller_exists($query[0]))
     $controller = $query[0]();
else throw new Exception('Controller not found: '.$query[0]);