I promise I have been looking for hours for the answer here, but it’s still not working. Here’s what I have:
RewriteCond %{HTTP_HOST} ^([^\.]*)\.example\.com [NC]
RewriteCond %{REQUEST_URI} !^/%1/ [NC]
RewriteRule ^(.*)$ /%1/$1 [L]
This creates an infinite loop because line two is not matching correctly. However, if I replace %1 in line two with www and go to www.example.com, it works fine. Obviously it no longer works for the other subdomains, but the fact that when I explicitly enter www in line two instead of letting %1 take care of it is strange, because I know the value of %1 is www.
What I’m trying to accomplish is as follows:
I have a domain “example.com”. In the root directory there are several subdirectories, let’s say “dev”, “test” and “www”. Higher up in my htaccess file I have a rule that forces the domain to redirect to “www.example.com” if the subdomain is empty (example.com), w (w.example.com), or ww (ww.example.com), anything else is left alone (dev.example.com, test.example.com). Now this part of the file is supposed to rewrite the request to the correct subdirectory based on the subdomain. So, a request like “dev.example.com/something.jpg” gets rewritten (not redirected) to “dev.example.com/dev/something.jpg”.
The plan here is to be able to create a development and testing environments on the server, without having to recreate an environment on my home server, making sure all the server settings are exactly the same. Also, it could do anything else I wanted it to do I suppose, but that’s the immediate need.
The problem is that you can’t use a backreference variable in the match expression of a
RewriteCond. This is OK:But this is not:
Something you could do if you needed to do a match like this is use match backreference
\1to access a match from within the same regular expression. You can then put the%1back reference in the same left side parameter ofRewriteCondand use\1to match against it. Something like this:So the
%{REQUEST_URI}:%1bit could look something like this:/foo:subdomain, and^/([^/]+)[^:]*:\1won’t match because the expression is looking for foo after the “:” (\1= “foo”). So the rule gets applied and the URI is now/subdomain/foo, and the second time around,%{REQUEST_URI}:%1becomes/subdomain/foo:subdomain, this time the regular expression matches because\1= “subdomain” and the!makes it so the rule doesn’t get applied.