修改Mod_rewrite规则以将文章标题添加到URL

时间:2011-07-13 13:18:18

标签: php mod-rewrite

我搜索了SO,但这里的所有例子都不适合我。

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

3 个答案:

答案 0 :(得分:1)

尝试类似的东西:

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

稍后添加:id之后的所有内容都将出现在other_params GET param中。

答案 1 :(得分:1)

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

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

$表示网址的结尾,但您想要在ID之后的内容,您应该将其删除

答案 2 :(得分:0)

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

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

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

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