doukao8851 2012-03-02 09:10
浏览 6
已采纳

htaccess和php - 重定向和漂亮的网址

I have a webcommunity, and it's growing now. I like to do a link makeover for my web, and then I need to know the best solution for my case.

Right now my htaccess looks kind of like this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)/?$ index.php?page=user&username=$1 [L]

You are able to link to users like this domain.com/username and that's nice.

Then I have different pages like

  • index.php?page=forum&id=1
  • index.php?page=someotherpage&id=1&anotherid=5
  • index.php?page=3rd

... and so on. I want them to look something like this:

  • domain.com/forum/23/title-of-the-thread
  • domain.com/page2/id1/id2

... and so on.

How do I make these pretty urls without removing my domain.com/username functionality? What solution would you suggest?

I was thinking about creating a file that checks the URL, if it matches any pages, and users and so on. Then it will redirect with a header location.

  • 写回答

4条回答 默认 最新

  • dtf76989 2012-03-02 09:29
    关注

    If all of the urls you are going to rewrite are going to the same end point, you could simply use:

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
    

    in index.php:

    <?php
    $url = $_SERVER['REQUEST_URI'];
    

    How you use the request uri is up to you, you could for example use a simple strpos check:

    <?php
    $url = $_SERVER['REQUEST_URI'];
    
    $rules = array(
        '/forum/' => 'forum',
        '/foo/' => 'foo',
        '/' => 'username'
    );
    
    foreach($rules as $pattern => $action) {
        if (strpos($url, $pattern) === 0) {
            // use action
            $file = "app/$action.php";
            require $file; 
            exit;
        }
    }
    // error handling - 404 no route found
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!