While there are a lot of questions dealing with this topic, I still cannot wrap my head around this particular case... So here is a generic example, that should illustrate my problem:
So, I have an Apache server, that does some proxying. My "application" is in htdocs/mydir
, which is where the .htaccess
is, as well.
I have the following rule in the .htaccess
, that works:
RewriteCond %{REQUEST_URI} ^/mydir/pics/first(/.*)? [OR]
RewriteCond %{REQUEST_URI} ^/mydir/pics/second(/.*)? [OR]
RewriteCond %{REQUEST_URI} ^/mydir/pics/third(/.*)?
RewriteRule ^pics/(.*)$ http://192.168.7.13:5055/$1 [P,L]
So, when I trigger the address http://localhost/mydir/pics/first/IMG12.jpg
in my browser, Apache gets this request proxied/forwarded to http://192.168.7.13:5055/IMG12.jpg
, which is what I'd want in this case. (Note that there could be 3rd level subdirectories other than "first", "second" or "third", which I would not like processed as above).
Now, the thing is, that I have several "subdirectories" under mydir
that I'd like to handle besides pics
- say, also videos
, drawings
, songs
etc. So, I'd like to avoid repeating all of the above rules for each and every subdirectory, and use some kind of a variable instead, that will be extracted from the request.
I'm aware that I can capture the subdirectory portion in an environment variable - this rule also works for me, and sets the SUBDIR variable to whatever the right subdirectory is in the request:
RewriteCond %{REQUEST_URI} ^/mydir/(pics|videos|drawings|songs)(?:/.*)?
RewriteRule ^ - [E=SUBDIR:%1]
Now, the problem is - how could I use this variable as a stand-in for the verbatim subdirectory in the proxying RewriteRule? As noted in other questions like What Double Colon does in RewriteCond? , %N backreference inside RewriteCond - this does not work:
RewriteCond %{REQUEST_URI} ^/mydir/(pics|videos|drawings|songs)(?:/.*)?
RewriteRule ^ - [E=SUBDIR:%1]
RewriteCond %{REQUEST_URI} ^/mydir/%{SUBDIR}/first(/.*)? [OR]
RewriteCond %{REQUEST_URI} ^/mydir/%{SUBDIR}/second(/.*)? [OR]
RewriteCond %{REQUEST_URI} ^/mydir/%{SUBDIR}/third(/.*)?
RewriteRule ^%{SUBDIR}/(.*)$ http://192.168.7.13:5055/$1 [P,L]
... because of limitations of what can be used in left-hand-side vs. right-hand-side of RewriteRule vs RewriteCond (which I still cannot understand fully).
However, looking at this example - would it somehow be possible to rewrite the above, so a variable is used to extract the 2nd level subdirectory, and it is then used to match in the RewriteRule?