5

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?

1

2 Answers 2

8

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 
Sign up to request clarification or add additional context in comments.

1 Comment

You can use a wildcard with a virtual document root. See Update 4 of this question: stackoverflow.com/questions/16747013/…
0

This is what I use with my freelancer work:

Under httpd-vhosts.conf:

UseCanonicalName Off <VirtualHost *:${AP_PORT}> DocumentRoot ${US_ROOTF_WWW}/_client ServerName client ServerAlias client <Directory "${HOME}\www\_client"> Require all granted </Directory> </VirtualHost> <VirtualHost *:${AP_PORT}> VirtualDocumentRoot "${US_ROOTF_WWW}/_client/%1" ServerName subdomains.client ServerAlias *.client <Directory "${HOME}\www\_client\*"> Require all granted </Directory> </VirtualHost> 

Then under the windows hosts file place the domain and subdomains that are needed.

127.0.0.1 client 127.0.0.1 someone.client 127.0.0.1 someone2.client 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.