I try to use the first part of the fqdn as a rewrite target:
http://demo.dev.example.com/something => http://demo.dev.example.com/demo/something
RewriteCond %{HTTP_HOST} ^([a-z0-9-]+).dev.example.com [NC]
RewriteRule ^/(.*) http://%1.dev.example.com/%1/$1 [P]
This creates an endless loop. So I need another condition that checks if this request is already rewritten or not:
RewriteCond %{REQUEST_URI} !^/%1
Well this is not working, the documentation says nothing about using backreferences in CondPatterns, most possibly it's not supported.
RewriteCond %{REQUEST_URI} !^/demo
This works perfectly, but isn't dynamic.
Solution/Workaround: reserve one hostname part for internal requests:
If you don't need to process any rules after the rewrite, just add the "L" = "last" option in the square brackets:
RewriteRule ^/(.*) http://%1.dev.example.com/%1/$1 [P,L]