Apache rewrite rule which works with or without a

2020-05-25 22:58发布

I'm trying to redirect a series of static URLs, and I want it to work whether or not the trailing slash is present:

/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?

4条回答
Evening l夕情丶
2楼-- · 2020-05-25 23:29

This also works: RedirectMatch 301 /foo/bar(/.*|$) http://url.com/tacos

查看更多
smile是对你的礼貌
3楼-- · 2020-05-25 23:30

Try

RewriteRule ^foo/bar/?$ http://url.com/tacos
查看更多
男人必须洒脱
4楼-- · 2020-05-25 23:34

Other than in EBNF or ABNF, a quantifier in regular expressions refers the preceding expression and not the following expression.

So:

RewriteRule ^foo/bar/?$ http://url.com/tacos
查看更多
姐就是有狂的资本
5楼-- · 2020-05-25 23:42

If you want to match foo/bar regardless of whether it's followed by another portion of path, you can say:

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.

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
查看更多
登录 后发表回答