如何使这个htaccess正确重定向

时间:2013-05-08 08:55:08

标签: php regex .htaccess mod-rewrite

我想使用htaccess RewriteRule重定向此网址:

news/tags/video to news.php?t=video
news/tags/interview to news.php?t=interview
news/tags/news to news.php?t=news 

网址:news.php?t=video, news.php?t=interview, news.php?t=news工作正常,我正确地记录了“t”var。但是当我申请htaccess RewriteRules时,“t”var没有通过。

这是我的代码:

<IfModule mod_rewrite.c>
    #this rules are working fine
    RewriteRule ^news[/]?$ news.php
    RewriteRule ^news/(.+)[/]?$ news_article.php?idN=$1

    #problem rules
    RewriteRule ^news/tags/video[/]?$ news.php?t=video
    RewriteRule ^news/tags/interview[/]?$ news.php?t=interview
    RewriteRule ^news/tags/news[/]?$ news.php?t=news
</IfModule>

3 个答案:

答案 0 :(得分:1)

模式^news/(.+)[/]?$匹配news/tags/video(等)并将网址重写为news_article.php,无法进一步匹配。你需要稍微调整一下这条规则:

RewriteRule ^news/?$ news.php
RewriteRule ^news/([^/]+)/?$ news_article.php?idN=$1
RewriteRule ^news/tags/video/?$ news.php?t=video
RewriteRule ^news/tags/interview/?$ news.php?t=interview
RewriteRule ^news/tags/news/?$ news.php?t=news

答案 1 :(得分:1)

重写按匹配顺序处理。如果存在其他返回true的规则,则首先您的重定向状态可能不匹配。在您的情况下,在达到附加规则之前会找到匹配项。

<IfModule mod_rewrite.c>
  RewriteRule ^news/tags/([^/]+)/?$ news.php?t=$1 [L]
  RewriteRule ^news[/]?$ news.php [L]
  RewriteRule ^news/([^/]+)[/]?$ news_article.php?idN=$1 [L]
</IfModule>

答案 2 :(得分:0)

请在代码中更改此RewriteRule指令:

RewriteRule ^news/(.+)[/]?$ news_article.php?idN=$1

...到这一个:

RewriteRule ^news/([^/]+)[/]?$ /news_article.php?idN=$1

因为之前的规则与所有内容匹配,包括“/”斜杠。只需使用下面的这条规则作为#problem rules的解决方案:

RewriteRule ^([^/]+)/tags/([^/]+)[/]?$ /$1.php?t=$2