24

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?

Luke Dennis
  • 14,212
  • 17
  • 56
  • 69
  • Ran into the same issue. I noticed that if I had the folder existing (but empty) then both would work with "RewriteRule ^old/(.*) http://test.com/new/$1 [R=301,L]" logic (where test.com/old/ existed). – Xonatron Jan 07 '19 at 18:33

4 Answers4

46

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
Community
  • 1
  • 1
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 8
    The question mark says "I'll have 0 or 1 trailing slashes." You go to a restaurant and say "I'll have a taco?" You're really saying "I'll have 0 or 1 tacos." – bobobobo Dec 22 '10 at 22:57
14

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
fulv
  • 1,016
  • 1
  • 9
  • 18
3

Try

RewriteRule ^foo/bar/?$ http://url.com/tacos
chigley
  • 2,562
  • 20
  • 18
1

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

CragMonkey
  • 808
  • 1
  • 11
  • 22