I'm trying to use RewriteMap in a apache 2.4 virtualhost .conf file to redirect a number of URLs. A variety of requests can refer to a single entry in the map and I'm having trouble matching these variants in the RewriteRule, particularly trailing slashes. I currently have something like:
RewriteRule "^/foo/(this|that|anotherthing)/bar/(.*)" "/${map:$2}"
this works fine giving
/for/that/bar/request
/for/this/bar/request
the same substitution, but I need to also provide the same substitution when the path has a trailing slash + any additional characters, ie,
/foo/this/bar/request/
/foo/this/bar/request/and/some/change
should all return the same value based on the match on "request". I can't seem to nail down the correct regex to match on 0 or 1 / and any additional characters to the end of the string. It has me thinking I'm misunderstanding an important piece of rewrites. Do I need to use a RewriteCond? I was hoping something simple like
RewriteRule "^/foo/(this|that|anotherthing)/bar/(.*)(\/.*?|)" "/${map:$2}"
would work but so far no luck.
You are most of the way there. Try this:
RewriteRule "^/foo/(this|that|anotherthing)/bar/(.+)(\/.+)?" "/${map:$2}"
I removed the pipe in the second capture group and moved the question mark to the outside. This makes the entire capture group optional, and if it is present then it must start with a forward slash.
I also changed the
.*
instances to.+
since you likely want to match on at least 1 character.Edit:
To also make the trailing slash optional, just add
\/?
to the end. If the second capture group is empty it will have no baring on this trailing slash check.RewriteRule "^/foo/(this|that|anotherthing)/bar/(.+)(\/.+)?\/?" "/${map:$2}"