Search code examples
phpregexapache.htaccesssubdomain

How can i map a multi level sub domain with sub folder


I have the following multi level sub domains:

  • aaa.bbb.ccc.app.example.com
  • xxx.yyy.zzz.app.example.com
  • 111.222.333.app.example.com

And the content (index.html, css, JavaScript) for these domains are located on:

  • root/aaa/bbb/ccc
  • root/xxx/yyy/zzz
  • root/111/222/333

Where by all initial domain levels point to root.

In .htaccess how do i go about pointing these domains (no redirects) to their respective folders? So far I have the following:

RewriteCond %{HTTP_HOST} ^(.*)\.(.*)\.(.*)\.app.example\.com
RewriteRule ^$ /%1/%2/%3/$1 [L,NC,QSA]

But the problem with this code is that although it points to the correct folder, it only displays the "index.html" files all other content (css, javascript...) comes up as 404 error.

For example:

root/aaa/bbb/ccc/style.css

should also be accessible via

aaa.bbb.ccc.app.example.com/style.css

But i get 404 for aaa.bbb.ccc.app.example.com/style.css


Solution

  • Your problem is in RewriteRule pattern which is ^$ so it matches URIwhich start ^ then end $ , means No URI and in this case it matches only request aaa.bbb.ccc.app.example.com/ and that why you said index.html.

    So , change this line :

    RewriteRule ^$ /%1/%2/%3/$1 [L,NC,QSA]
    

    By this :

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

    UPDATE : you should exclude the given directories to avoid looping :

      RewriteCond %{HTTP_HOST} ^(.*)\.(.*)\.(.*)\.app\.example\.com
      RewriteCond %{REQUEST_URI} !^/(aaa|xxx|111)/
      RewriteRule ^ /%1/%2/%3%{REQUEST_URI} [L,NC,QSA]