'how to dynamically rewrite filepath .htaccess based on domain?

I have this apache rule in my .htaccess file:

RewriteCond %{HTTP_HOST} ^testURL.localhost.local
RewriteRule ^index.php$ /_testURL/index.php [L]

How would I write this so that testURL2.localhost.local or any other subdomain would be rewritten to the corresponding directories?

For instance testURL2.localhost.local would be rewritten to _testURL2/index.php etc

I already tried the option below but I didn't get the intended result:

RewriteCond %{HTTP_HOST} ^testURL
RewriteRule ^cms.php$ /_%1/cms.php [L]


Solution 1:[1]

With your shown samples, attempts; please try following htaccess rules file. I have posted 2 sets of htaccess rules file here, you have to use ONLY one set at a time.

1st solution: This is specifically for host testURL.localhost.local and will look for either index.php OR cms.php only in UI.

RewriteEngine ON
RewriteCond %{HTTP_HOST} ^(?:www\.)?(testURL)\.localhost\.local$ [NC]
RewriteRule ^((?:index|cms)\.php)$  _%1/$1 [NC,L]


2nd solution: A Generic solution, where it will look for anyvalue.localhost.local and it will add anyvalue in path while rewriting, also it will look for any php files in uri.

RewriteEngine ON
RewriteCond %{HTTP_HOST} ^(?:www\.)?([^.]*)\.localhost\.local$ [NC]
RewriteRule ^([^.]*\.php)$  _%1/$1 [NC,L]

NOTE1: Also please make sure to clear your browser cache before testing your URLs.

NOTE2: Please keep these rules at the top of your htaccess rules file.

NOTE3: I am also additionally/optimally matching www. in host in case you don't want it you could remove it (?:www\.)? part in condition.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1