简体   繁体   English

Apache重写规则,可以使用或不使用尾部斜杠

[英]Apache rewrite rule which works with or without a trailing slash

I'm trying to redirect a series of static URLs, and I want it to work whether or not the trailing slash is present: 我正在尝试重定向一系列静态URL,无论是否存在尾部斜杠,我希望它能够正常工作:

/foo/bar  --->  /tacos
/foo/bar/  -->  /tacos

I've tried the following, and all sorts of variations, but I always get a match only with the trailing slash present: 我尝试过以下各种各样的变化,但是我总是只得到一个匹配的斜杠:

RewriteRule ^foo/bar?/$ http://url.com/tacos
RewriteRule ^foo/bar(?/)$ http://url.com/tacos
RewriteRule ^foo/bar*/$ http://url.com/tacos
RewriteRule ^foo/bar(*/)$ http://url.com/tacos

I feel like I'm missing something obvious. 我觉得我错过了一些明显的东西。 Help? 救命?

Other than in EBNF or ABNF , a quantifier in regular expressions refers the preceding expression and not the following expression. 除了在EBNFABNF中 ,正则表达式中的量词指的是前面的表达式而不是下面的表达式。

So: 所以:

RewriteRule ^foo/bar/?$ http://url.com/tacos

If you want to match foo/bar regardless of whether it's followed by another portion of path, you can say: 如果你想匹配foo / bar,无论它是否跟着路径的另一部分,你可以说:

RewriteRule ^foo/bar(/.*|$) http://url.com/tacos

This will match any of the following: 这将符合以下任何一项:

foo/bar
foo/bar/
foo/bar/baz

It means: match either a) a slash followed by 0 or more characters, or b) the end of the string. 它表示:匹配a)斜杠后跟0或更多字符,或b)字符串结尾。

On the other hand, these might be undesirable: 另一方面,这些可能是不受欢迎的:

RewriteRule ^foo/bar/? http://url.com/tacos     # This also matches foo/barb
RewriteRule ^foo/bar/?$ http://url.com/tacos    # This will not match foo/bar/baz

尝试

RewriteRule ^foo/bar/?$ http://url.com/tacos

这也有效: RedirectMatch 301 /foo/bar(/.*|$) http://url.com/tacos

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM