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条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化