Apache RewriteCond: inject string into URI between regex match groups

apache-2.4datemod-rewriteregexuri

EDIT
This works, needed to use % in place of $ for capture groups:

RewriteRule (.*) http://localhost:8081/%1/%{TIME_YEAR}1101%2 [P]

Having a hard time sorting this out.

Need a date string conditionally injected into specific URIs (for proxy to Jetty app server), the condition being, if no 8-digit date string already present, inject it.

The hack I came up with is:

RewriteCond %{REQUEST_URI} ^/(foo|bar|baz)(.*)
RewriteCond %2 !/(\d{8})(.*)
RewriteRule (.*) http://localhost:8081$1/%{TIME_YEAR}1101$2 [P]

This works to some degree, but not all in that $2 is empty, $1 matches the entire URI.

Basically what winds up happening is a request for /foo/2 gets rewritten to /foo/2/20121101, while what I need to have happen is /foo/20121101/2

So, given that $1 matches the entire URI, how can I get it to match only foo|bar|baz, leaving $2 as the URI remainder with which I can then sandwich in the date?

Also, is this an horribly inefficient approach? Apache docs usually indicate chaining [OR]s so not sure if straight regex is the way to go (certainly more concise). On Apache 2.4 so hoping to actually benefit from the speed enhancements (vs. shooting self in the foot)

Thanks

Best Answer

If I understand what you're doing right, which I may not, I'd say it can be simpler:

RewriteCond %{REQUEST_URI} !/\d{8}(/|$)
RewriteRule ^/(foo|bar|baz)(/?.*)$ http://localhost:8081/$1/%{TIME_YEAR}1101$2 [P]