Domain and subdomain wildcards on Apache as dynamic subfolders
I am creating a website builder like weebly
and wix
. I would like dynamic subfolders. For example:
domain.com /public_html/sites/domain.com/
sub1.root.com /public_html/sites/sub1/
test.com /public_html/sites/test.com/
sub2.root.com /public_html/sites/sub2/
I can only do static
with the following and made me add whole sites one by one.
<VirtualHost *:80>
DocumentRoot "/public_html/sites/domain.com"
ServerName domain.com
ServerAlias *.domain.com
</VirtualHost>
How can I make both domains dynamic as the owner and subdomains of the client that I will give to the user.
source to share
/public_html/sites/
You can use ServerAlias
and to configure a dynamic domain name based on folder names created in VirtualDocumentRoot
.
Add the following to your apache virtualhost config file:
<VirtualHost *:80>
...
ServerAlias *
VirtualDocumentRoot /public_html/sites/%0
...
</VirtualHost>
To understand why % 0 is used , consider a domain m.rate.movies.net
split into parts
Index: %1 %2 %3 %4
Domain: m rate movies net
Negative Index: %-4 %-3 %-2 %-1
The one I decided to use %0
represents the fully qualified domain name - m.rate.movies.net
. This allows you to support domain names that can have different numbers of dots separated. This makes the subdirectories created internally the /public_html/sites/
document root for any domain name pointing to your server IP.
/public_html/sites/domain.com --> http://domain.com/
/public_html/sites/blog.writers.org --> http://blog.writers.org/
/public_html/sites/m.rate.movies.net --> http://m.rate.movies.net/
If you used something like VirtualDocumentRoot /public_html/sites/%1
You will need to create subdirectories this way
/public_html/sites/domain --> http://domain.com/
/public_html/sites/blog --> http://blog.writers.org/
/public_html/sites/m --> http://m.rate.movies.net/
You can also use a combination: VirtualDocumentRoot /public_html/sites/%-2\.%-1
/public_html/sites/domain.com --> http://domain.com/
/public_html/sites/writers.org --> http://blog.writers.org/
/public_html/sites/movies.net --> http://m.rate.movies.net/
Another way: VirtualDocumentRoot /public_html/sites/%-1/%-2/
/public_html/sites/com/domain --> http://domain.com/
/public_html/sites/org/writers --> http://blog.writers.org/
/public_html/sites/net/movies --> http://m.rate.movies.net/
With this setup, you don't have to edit the virtual host configuration every time you add a new domain. You won't be able to use separate log files for each domain, but for this you can use a custom log that includes the hostname.
source to share