开发者

Variable/Dynamic/REGEX Virtualhost in Apache?

Just an off the wall question today. Is it posible to vary DocumentRoot of a virtualhost based on the subdomain requested like so?

<VirtualHost *>
   ServerName ^VARIABLE$.example.com
 开发者_C百科  DocumentRoot ~/Sites/^VARIABLE$
</VirtualHost>


Yes it is possible:


Step1: Setting up Wildcard DNS

You have to add an A Record that points to your server's IP like that:

*.example.com.    IN      A       192.168.1.1

Step2: Set up apache VirtualHost

<VirtualHost *>
        ServerName  www.example.com
        ServerAlias *.example.com

        DirectoryIndex index.html 
        DocumentRoot /home/www/www.example.com/htdocs
    ....
</VirtualHost>

Notice the important line: ServerAlias *.example.com. This will tell Apache that any host with the .example.com suffix will match this virtual host too.

Step3: Setting up Rewrite Rules

You have to add this lines in your .htaccess file located in your web root folder (eg. /home/www/www.example.com/htdocs):

RewriteEngine on
RewriteCond %{http_host} .
RewriteCond %{http_host} !^www.example.com [NC]
RewriteCond %{http_host} ^([^.]+)\.example.com [NC]
RewriteRule ^(.*) http://www.example.com/%1/ [R=301,L,QSA] 

That way a request for foo.example.com will redirect visitors to example.com/foo and so on. Good luck.


(Reference: http://www.debian-administration.org/articles/358)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜