Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache: virtualhost on each sub-domain to corresponding directory

I would like to do something like this:

<VirtualHost *:80>
  ServerName $variable.example.com
  DocumentRoot /var/www/$variable
</VirtualHost>

for example if I go to foo.example.com it must show me /var/www/foo directory content

What is the good apache syntax for that?

like image 725
Yukulélé Avatar asked Sep 12 '13 08:09

Yukulélé


1 Answers

You can't have $variable like that in servername and map it to the document root, but you can use mod_rewrite and a wildcard.

<VirtualHost *:80>
  ServerName subdomain.example.com
  ServerAlias *.example.com
  DocumentRoot /var/www/

  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteCond %{HTTP_HOST} ^([^.]+)\.
  RewriteCond %{REQUEST_URI}::%1 !^/([^/]+).*::\1
  RewriteRule ^(.*)$ /%1/$1 [L]
</VirtualHost>

The subdomain.example.com can just be any subdomain that isn't www.example.com. For any request that doesn't start with "www", the subdomain is captured as a group (2nd condition), then the next line makes sure the request isn't already being routed into the subdomain's name, and the rule routes it.

So for the request:

http://foo.example.com/bar/x.html

it gets routed to:

/foo/bar/x.html
like image 149
Jon Lin Avatar answered Nov 11 '22 17:11

Jon Lin