UrlRewrite规则不起作用


UrlRewriting rule does not work

我有以下PHP代码:

   <?php  
    if(isset($_GET['article']))
    {
        echo "<b>success</b>";
    }
 ?>

这个html:

<a href="http://localhost/PHPTest/index.php?article_27" >Click me</a>

我正在努力想出我自己的网址。

通过这样做,我尝试使用mod_rewrite()。这就是我的。htaccess:

RewriteEngine On
RewriteBase /PHPTest/
RewriteRule ^article_([0-9]+)$ index.php?article=$1

正如你所看到的,我试图让这篇文章变得可变。。

但是这不起作用。。htaccess不理解artcile_27,例如,因为article=27.

为什么?

应该发生的是,每当我按下链接时,成功的单词都应该打印出来。问题是它没有。

您编写的规则将与链接匹配http://localhost/PHPTest/article_27,如果你真的想拥有URLhttp://localhost/PHPTest/index.php?article_27匹配(至少在我看来,这是一个不寻常的URL),正确的重写规则如下:

RewriteRule ^index'.php'?article_([0-9]+)$ index.php?article=$1

你必须看最后一个斜线之后的整个部分。

您的规则应该是:

RewriteRule ^index.php?article_([0-9]+)$ index.php?article=$1

然而,我会质疑以这种方式使用mod_rewrite。

首先,如果你的url总是只有index.php?article_27,那么你可以使用$_SERVER['QUERY_STRING']直接访问"article_27",而不需要mod_rewrite。

如果您要使用mod_rewrite,为什么不将您的URL设置为/PHPTest/article/27

RewriteRule ^article/([0-9]+) index.php?article=$1

以上内容还将允许/PHPTest/article/27/title_of_article_here,它为您提供了两个好处:ID仍然存在,因此很容易在服务器端检索,名称在URL中,因此作为一个人阅读很好,并有助于搜索引擎。如果你现在查看你的URL栏,你会注意到stackoverflow本身使用了这个方法。

打开这个:http://localhost/PHPTest/article_27

如果它有效,就意味着你的重写有效。在这种情况下,您所要做的就是更改HTML:

<a href="http://localhost/PHPTest/index.php?article_27" >Click me</a>

应为:

<a href="http://localhost/PHPTest/article_27" >Click me</a>

或者更确切地说,只是:

<a href="/PHPTest/article_27" >Click me</a>

这使您的代码更易于移植到另一个主机名、端口、协议。。。