如何制作htaccess动态和静态规则?

时间:2013-01-17 12:09:09

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

我有这个动态规则:

RewriteRule ^(.*)/(.*)$ /rewrite.php?sub=$1&second=$2 [NC]

我试图添加一些这样的静态规则:

RedirectMatch 302 /construction/pools.html http://www.{samedomain}.com/construction-services/pools

问题是当我在地址栏中输入以下内容时:

http://www.{samedomain}.com/construction/pools.html

然后apache重定向到:

http://www.{samedomain}.com/construction-services/pools?sub=construction&second=pools.html

我想要的是apache重定向到:

http://www.{samedomain}.com/construction-services/pools

有人知道为什么吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

重定向按照它们出现的顺序进行处理,因此应该将静态重定向放在RewriteRule之前。不要在[L]上获得RewriteRule标记。

RewriteEngine On
# Match the static redirect first
RedirectMatch 302 /construction/pools.html http://www.{samedomain}.com/construction-services/pools

# Since your dynamic URLs don't end in .html, avoid those with RewriteCond
RewriteCond %{REQUEST_URI} !\.html$
RewriteRule ^([^/]+)/(.*)$ /rewrite.php?sub=$1&second=$2 [NC,L]

如果您的动态网址都没有RewriteCond

,您可以在没有.的情况下执行此操作
RewriteRule ^([^/]+)/([^.]+)$ /rewrite.php?sub=$1&second=$2 [NC,L]

答案 1 :(得分:1)

根据优先级编写htaccess规则(最后放置具有共同行为的规则)

在你的情况下

RedirectMatch 302 /construction/pools.html http://www.{samedomain}.com/construction-services/pools
RewriteRule ^(.*)/(.*)$ /rewrite.php?sub=$1&second=$2 [NC]