URL重写规则不起作用
我有下面的PHP代码:URL重写规则不起作用
<?php
if(isset($_GET['article']))
{
echo "<b>success</b>";
}
?>
而且这个网站:
<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 ..
这是为什么?
什么应该发生的是,当我按下链接时,应该打印成功的词。问题是它没有。
您的规则应该是:
RewriteRule ^index.php?article_([0-9]+)$ index.php?article=$1
不过,我会质疑这种方式使用mod_rewrite的。
首先,如果您的网址总是只有index.php?article_27
,那么您可以直接在“article_27”上使用$_SERVER['QUERY_STRING']
,而不需要mod_rewrite。
如果你打算使用mod_rewrite,为什么不让你的网址为/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>
使您的代码更容易移植到另一个主机名,端口,协议...
你写的规则将匹配链接http://localhost/PHPTest/article_27,如果哟ü真的希望有URL http://localhost/PHPTest/index.php?article_27匹配(这是一个,至少在我的oppionion,不寻常的URL),正确的重写规则将是以下几点:
RewriteRule ^index\.php\?article_([0-9]+)$ index.php?article=$1
你不得不看后的整体的一部分最后的斜线。
哇..令人难以置信的是,我被困在这个问题上一整天! – BlackFire27 2012-03-26 16:56:20