Mod-rewrite rule not catching trailing slash in pattern

I have a rewrite rule that is supposed to match:


and redirect to:


The rule is RewriteRule ^(.*)?/Lodg(e|ing)/(.*)?$ $1/Hotels/ [NC,R=301]

It matches without the trailing slash but will not see a url with one.  I have tried the following variations:

RewriteRule ^(.*)?/Lodg(e|ing)/?(.*)?$ $1/Hotels/ [NC,R=301]
RewriteRule ^(.*)?/Lodg(e|ing)/?$ $1/Hotels/ [NC,R=301]

I can't get a PREG tester to tell me what's going on so I'm basically at a loss with this one.
Who is Participating?
HackneyCabConnect With a Mentor Commented:
Okay, I had to resort to tampering with my own server's .httaccess file, but this works for me:

RewriteRule ^(.*/|)Lodg(e|ing)/? /$1Hotels/ [L,R=permanent]

If you move it to a server-wide httpd.conf file it will need to change, though, as httpd.conf is not directory specific.

This rule allows for as well, so let me know if you don't permit Lodge to be the first directory in the path.
Try this

RewriteRule ^(.*)/Lodge(e|ing)/?$ $1/Hotels/ [NC,R=permanent]

And if you need to allow (but ignore) filenames after the Lodging part, this instead:

RewriteRule ^(.*)/Lodge(e|ing)(?:$|/$|/[^/]+$) $1/Hotels/ [NC,R=permanent]
GoTravelAuthor Commented:
@HackneyCab: No dice, doesn't work on the non-slash URL's either.  What is going on in "(?:$|/$|/[^/]+$)"?
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

GoTravelAuthor Commented:
Additional, perhaps key note.  If I remove the leading slash so that the rule looks like this:

RewriteRule ^(.*)?Lodg(e|ing)/(.*)?$ $1/Hotels/ [NC,R=301]

Then my trailing slash problem goes away, but I then match any URL with the words 'Lodge' or 'Lodging' at the end.
The (?:$|/$|/[^/]+$) pattern just allows the end, or a slash and the end, or a slash, and then any number of non-slash characters until the end.

Can you list exactly what should be matched. I'm not clear on what is allowed to come before or after the term /Lodge/ or /Lodging/.
GoTravelAuthor Commented: or

OR or

Anything after should be ignored.

Doesnt "[^/]" mean no slashes?  I thought ^ within a character class was the negation.
GoTravelAuthor Commented:
Quick mod of the rule, possible because this Apache lives on Windows, I removed the leading slash from the redirect: $1Hotels/

With the leading slash it would redirect to include the OS filesystem path, which is an interesting but Bad Thing.  Thank you for the rule and swift production of it.
Glad to be of help.

I'm on Linux, so I'm not sure how Windows handles Apache differently, but it does seem strange that the first slash takes the path to the drive root, rather than the web root. Have you set the DocumentRoot directive so that Apache knows where its web root lies?

Anyway, good luck with your project.
All Courses

From novice to tech pro — start learning today.