如何让htaccess捕获所有重写规则?

时间:2013-03-07 15:30:09

标签: .htaccess mod-rewrite

我有一系列的回报来查看和处理消息中心:

RewriteRule ^messages/process/([a-zA-Z_-]+)/([0-9]+)/?$ messages-process.php?do=$1&id=$2 [L]
RewriteRule ^messages/process/ajax/([a-zA-Z_-]+)/?$ messages-process.php?do=$1&ajax=true [L]
RewriteRule ^messages/view/([0-9]+)/?$ messages.php?page=view&id=$1 [L]
RewriteRule ^messages/([a-zA-Z_-]+)/?$ messages.php?page=$1 [L]
RewriteRule ^messages/?$ messages.php [L]

我的问题是,我如何设置一个可以作为全部捕获的规则,因此如果有人浏览到/messages/process/,它们仍将以messages-process.php结尾,但不会设置所需的参数。< / p>

另一种看待它的方法是,如何使参数可选,重写仍然有效,但参数将丢失?

1 个答案:

答案 0 :(得分:1)

您对/messages/process/的请求与此规则匹配:

RewriteRule ^messages/([a-zA-Z_-]+)/?$ messages.php?page=$1 [L]

...因此,您需要一个更具体的规则,该规则先匹配/messages/process/,然后在匹配更通用的规则之前将其路由到messages-process.php

之前放置所有其他规则将完成该特定模式:

RewriteRule ^messages/process/?$ messages-process.php [L]

如果除process/以外的其他目录需要进行类似的重写,例如/messages/thingmessages-thing.php,请在之前使用此规则。您将需要明确列出那些以后不再与更通用的规则匹配的那些......

# Matches /messages/process/ or /messages/otherdirectory/, etc...
RewriteRule ^messages/(process|thing|otherdirectory|somethingelse)/?$ messages-$1.php [L]

总之,这应该做的工作:

# Matches /messages/process/ or /messages/otherdirectory/, etc...
RewriteRule ^messages/(process|thing|otherdirectory|somethingelse)/?$ messages-$1.php [L]
RewriteRule ^messages/process/([a-zA-Z_-]+)/([0-9]+)/?$ messages-process.php?do=$1&id=$2 [L]
RewriteRule ^messages/process/ajax/([a-zA-Z_-]+)/?$ messages-process.php?do=$1&ajax=true [L]
RewriteRule ^messages/view/([0-9]+)/?$ messages.php?page=view&id=$1 [L]
# Stuff not matched by the specific rule at the top matches this one...
RewriteRule ^messages/([a-zA-Z_-]+)/?$ messages.php?page=$1 [L]
RewriteRule ^messages/?$ messages.php [L]

更新

要允许像/messages/process/trash这样的网址一般被重写,您需要在此之后的规则:

RewriteRule ^messages/process/([a-zA-Z_-]+)/([0-9]+)/?$ messages-process.php?do=$1&id=$2 [L]
# Match stuff after /process/whatever which are not followed by digits (which the previous rule matches)
RewriteRule ^messages/process/([a-zA-Z_-]+)(?:/[^0-9]+/?)$ messages-proces.php [L]