Creating Wildcard Sub Domain Using Apache VirtualHost

Saint Robson picture Saint Robson · Nov 26, 2012 · Viewed 40.9k times · Source

I want to have this situation :

  1. if user request using this URL : example.com or www.example.com, user will see index.php in this directory /home/admin1/public_html/

  2. but when user request using other sub domain (wildcard) for example : freediscount.example.com, user will see index.php in this path : /home/admin1/public_html/userweb/freediscount.example.com

technical support on my hosting suggest me to use this method : http://www.wiredstudios.com/php-programming/setting-up-wildcard-dns-for-subdomains-on-cpanel.html

based on that tutorial, the PHP has a new job... to redirect on specific folder when user request with sub domain. I don't like this method. for me, it would be better if Apache can handle this.

nearly close to what I need is this method : Virtualhost For Wildcard Subdomain and Static Subdomain

but, I have a problem with VirtualHost setting, how to create VirtualHost correctly for that situation?

here's what I've done but didn't work :

## I think this one is for www or without www, automatically generated with WHM
<VirtualHost xx.xx.xx.xx:80> 
ServerName example.com
ServerAlias www.example.com
DocumentRoot /home/admin1/public_html
</VirtualHost>

## Here's what I'm trying to add
<VirtualHost xx.xx.xx.xx:80>
    ServerName example.com
    DocumentRoot /home/admin1/public_html/userweb/*
</VirtualHost>

Answer

Dan picture Dan · Jun 2, 2013

Wildcard sub-domains are definitely possible using Apache virtual hosts.

I had basically the same requirements and managed to get it working with Apache's mod_vhost_alias.so module. Try this in your http-vhosts.conf file:

DocumentRoot "/home/admin1/public_html/userweb/" 
<Directory "/home/admin1/public_html/userweb/"> 
    Options None 
    AllowOverride None 
    Order allow,deny 
    Allow from all 
</Directory>

<VirtualHost *:80>
    DocumentRoot /home/admin1/public_html/
    ServerName www.example.com
</VirtualHost>

<VirtualHost *:80> 
    VirtualDocumentRoot /home/admin1/public_html/userweb/%1.example.com/ 
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /home/admin1/public_html/
    ServerName example.com
</VirtualHost>

Note that I haven't tested this, but it's pretty close to the solution that worked for me.

Full details of my solution are here: http://www.calcatraz.com/blog/wildcard-subdomains-in-apache-1422