Htaccess rewriting all subdomains to subdirectories

.htaccessapache-2.2mod-rewrite

I'm trying to build a catch-all for any subdomains (not captured by previous rewrite rules) for a certain domain, and serve a website from a subdirectory that resides in the same folder as the .htaccess file. I already have my vhosts.conf to send all unmapped requests to a "playground" folder, where I want to easily create new subdomains by simply adding a subfolder.

So, my structure looks like this:

/var/www/playground
              |-> /foo
              |-> /bar

The .htacces living inside the /playground folder and /foo and /bar being seperate websites. I want http://foo.domain.com to point to /foo and http://bar.domain.com to /bar.

Here is my .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^([^.]+).domain.com$ [NC]
RewriteCond %{REQUEST_URI} !^/%1/(.*)
RewriteRule ^(.*) /%1/$1 [L]

This is supposed to capture the subdomain, add it as a subfolder in RewriteRule, then append after the slash and path information. The second RewriteCond is there to prevent an infinite loop. My idea was that %1 in the second RewriteCond would be able to capture the capture group in the first RewriteCond. But so far I haven't had any success, it's always ending up in a redirect loop. If I would replace %1 in the second RewriteCond with hardcoded 'foo' or 'bar', it works, which leads me to believe that you cannot refer to a capture group inside a RewriteCond. Is is true? Or am I missing something?

Best Answer

Hope I understood you correctly:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^([^.]+).domain.com$ [NC]
RewriteCond %{REQUEST_URI} !%1
RewriteRule ^(.*)$ /%1/$1 [L]
Related Topic