.htaccess url重写并重定向301

时间:2013-12-08 11:09:54

标签: .htaccess mod-rewrite redirect url-rewriting

目前我们有一个页面显示链接列表 每个链接都有自己的ID号

使用文件info.php打开每个链接?ID = X

例如:

www.mysite.com/info.php?ID=1 shows  the link "weather italy"
www.mysite.com/info.php?ID=2 shows  the link "weather france"

由于我们有“天气意大利”和“天气法国”的几个链接,我们想在.htacces中重写新的网址(天气 - 意大利和天气 - 法国) 对于新的网址,我们将拥有以下结构:

www.mysite.com/weather-italy/info.php?ID=1

www.mysite.com/weather-france/info.php?ID=2

使用以下代码,我们告诉服务器重写URL并调用原始文件:

RewriteRule    ^weather-italy/info.php?$    info.php    [NC,L]
RewriteRule    ^weather-france/info.php?$    info.php    [NC,L]

这很好用。

要避免 双重索引 ,我们希望将旧链接重定向301到新链接。

我们通过以下代码实现了这一目标:

RewriteCond %{THE_REQUEST} \?ID=1
RewriteRule ^info\.php$  http://www.touristinfo.fr/weather-italy/info\.php [L,R=301]

RewriteCond %{THE_REQUEST} \?ID=2
RewriteRule ^info\.php$  http://www.touristinfo.fr/weather-france/info\.php [L,R=301]

这也可以完成这项工作,但与脚本的第一部分相结合会产生一个永无止境的循环。

我们的代码有什么问题?

非常感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

如果您要匹配的网址是外部请求,则

%{THE_REQUEST}仅匹配。你的问题是你制作的正则表达式不够具体。

让我们来看看会发生什么。你去example.com/info.php?ID=2。前两个规则不匹配,但第四个规则不匹配。您最终会重定向到example.com/weather-france/info.php?ID=2

再次通过.htaccess。第二个规则匹配,并在内部将其重写为info.php?ID=2[L]标记在此处没有区别,因为该网址将通过.htaccess拉出,直到它停止更改为止。在.htaccess的第二个周期中,即使外部请求包含/weather-france/info.php?ID=2,网址也会匹配第4个规则。 ID=2也在外部请求中,内部重写现在再次info.php

修复方法是让%{THE_REQUEST}足够匹配,以便重写的网址不再匹配。

进一步说明:熟悉RewriteRuleRewriteCond中正则表达式和字符串之间的区别。你在一个字符串中逃脱了一个点,同时在未转义的正则表达式中留下了一个点。 ?是“匹配前一个字符0或1次”,而不是问号文字。查询字符串无法在RewriteRule的第一个参数中匹配。

你最终会得到:

RewriteRule ^weather-italy/info\.php$ info.php [NC,L]
RewriteRule ^weather-france/info\.php$ info.php [NC,L]

RewriteCond %{THE_REQUEST} ^(GET|POST)\ /info\.php\?ID=1
RewriteRule ^info\.php$  http://example.com/weather-italy/info.php [L,R]

RewriteCond %{THE_REQUEST} ^(GET|POST)\ /info\.php\?ID=2
RewriteRule ^info\.php$  http://example.com/weather-france/info.php [L,R]