dongpu42006096 2014-11-26 22:09
浏览 17
已采纳

htaccess中的友好URL

I have a problem with friendly url in .htaccess. I need something like this

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..

and

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

and

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

and

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

and

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

My .htaccess file:

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 

but something is wrong, for example http://example.com/& or http://example.com/< make error Not Found. Can someone help me?

  • 写回答

1条回答 默认 最新

  • drm30963 2014-11-26 22:33
    关注

    I think you'll have an easy time by using a more simple URL Rewrite rule and parse your url in PHP.

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

    And in your PHP something like

    // 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]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?