【问题标题】:Modify Mod_rewrite rule to add article title to URL修改 Mod_rewrite 规则,将文章标题添加到 URL
【发布时间】:2011-07-13 13:18:17
【问题描述】:

我已经搜索过,但这里的所有示例都不适合我。

I have a $_SESSION['title']; //Session variable contains title from calling page

$title = $_SESSION['title']; //local variable contains article title

假设文章的标题是每日新闻 如何将我的规则修改为

http://www.newstoday.com/readnews/12/news-of-the-day

BTW http://www.newstoday.com/readnews/12 //this works

RewriteEngine on
RewriteRule ^readnews/([0-9]+)$ readnews.php?news_art_id=$1

【问题讨论】:

    标签: php mod-rewrite


    【解决方案1】:

    试试这样的:

    RewriteEngine on
    RewriteRule ^readnews/([0-9]+)(/(.*))?$ readnews.php?news_art_id=$1&other_params=$3
    

    稍后添加:id 之后的所有内容都将在 other_params GET 参数中。

    【讨论】:

    • 如何在 html 内的锚链接中使用它?
    • 您的两个网址 newstoday.com/readnews/12/news-of-the-day newstoday.com/readnews/12 将重定向到 readnews.php 脚本,您可以从 $_GET['news_art_id'] 和 "news-of-the-day" 获得“12” " (对于第二种情况是 "") from $_GET['other_params'];从 php 生成这样的链接:$id = 0; // 假设这是你的 id $title = $_SESSION['title']; $link = 'newstoday.com/readnews' 。 $id 。 '/' 。 $title;
    【解决方案2】:

    您的正则表达式不正确。应该是:

    RewriteEngine on
    RewriteRule ^readnews/([0-9]+) readnews.php?news_art_id=$1
    

    $ 表示 URL 的结尾,但要在 id 后面有内容,应该去掉它

    【讨论】:

      【解决方案3】:

      首先,您需要确保 PHP 能够区分这两个 URL。

      RewriteRule ^readnews/([0-9]+)(\/[a-z-]+)?$ readnews.php?news_art_id=$1&title=$2
      

      如果 URL 中存在标题,这将使 $_POST['title'] 包含 news-of-the-day - 否则 $_POST['title'] 将为空。在此之后,您可以简单地检查它是否由 PHP 设置,如果不是则重定向:

      if (empty($_POST['title']))
        header("Location: /readnews/".$_POST['news_art_id']."/".$_SESSION['title']);
      

      【讨论】:

      • 按照你的例子......有一个像这样的锚链接是否正确?......News heline
      • 是的,/readnews/12/readnews/12/title 都应该可以工作。前者应该重定向到后者。
      猜你喜欢
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多