Htaccess – Wildcard subdomains to subfolders

.htaccessmod-rewritewildcard-subdomain

So the idea is that I have:

domain.com/.subdomains/domain1 (2,3,4,etc)

And I want to map:

domain1.domain.com -> domain.com/.subdomains/domain1/
domain2.domain.com -> domain.com/.subdomains/domain2/

But I want it to ignore "www"

I'm doing this semi-successfully with this:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com [NC]
RewriteRule ^(.*)$ http://domain.com/.subdomains/%1/$1 [NC,QSA,L,P]

There are two problems:

1) It's not ignoring the "www"

2) When I go to URL:

http://domain3.domain.com/deep/subfolder/here/index.html

it redirects me to:

http://domain.com/.subdomains/domain3/deep/subfolder/here/index.html

I've been trying to find answers, but I cannot find anyone else having this problem.
Any ideas?

Thanks!

EDIT:

Okay, seems that I can't use the http, but if I change

RewriteRule ^(.*)$ http://domain.com/.subdomains/%1/$1 [NC,QSA,L,P]

to

RewriteRule ^(.*)$ /.subdomains/%1/$1 [NC,QSA,L,P]

It goes to a weird redirect loop

Best Answer

I got it to work with this:

RewriteEngine on

RewriteBase /

# MAGIC
RewriteCond $1 !/$
RewriteCond $1 !\.
RewriteRule ^(.+)$ /$1/ [R=301,L]
# //MAGIC

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.domain\.com
RewriteCond %{REQUEST_URI} !^/.subdomains/
RewriteRule ^(.*)$ /.subdomains/%1/$1 [L]

I pretty much understand rest of the code, except the magic part - somehow it fixes this bug:

http://domain3.domain.com/deep/subfolder/here/index.html

To

http://domain.com/.subdomains/domain3/deep/subfolder/here/index.html

Right now that does not happen, thanks to the MAGIC... I wish I knew why it worked.

Related Topic