virtual subdomain: one subdomain per user

2019-02-25 07:30发布

问题:

On my website i'm using virtual host so my users can have virtual domain like 'user1.mydomain.com', 'user2.mydomain.com',...

The problem is that on virtual domains like 'user1.domain.com' the index page is always the same as on my index page 'http://mydomain.com'.

What i want to do is to have two different index pages for the domain and for subdomains. My question, how to have subdomains redirected to 'index2.php' (for example) and still have the subdomains to look like 'user1.mydomain.com'?

回答1:

Ideally, you would set up completely separate document directories for each subdomain. vhost in apache is the way to go. If you however want to do it your way (subdomains redirecting to individual files), then it's a bit more work, but is still doable. First, define the mod_vhost with wildcard:

<VirtualHost 111.22.33.55>
    DocumentRoot /www/subdomain
    ServerName www.mydomain.com
    ServerAlias *.mydomain.com

    ...
</VirtualHost>

Then inside this VirtualHost setup rewrite rules using mod_rewrite:

<Location "/">
    RewriteCond %{HTTP_HOST} ^user1.mydomain.com$
    RewriteRule ^\/$ http://www.mydomain.com/index2.php [R=301,L]
    RewriteRule ^\/index.php$ http://www.mydomain.com/index2.php [R=301,L]

    RewriteCond %{HTTP_HOST} ^user2.mydomain.com$
    RewriteRule ^\/$ http://www.mydomain.com/index3.php [R=301,L]
    RewriteRule ^\/index.php$ http://www.mydomain.com/index3.php [R=301,L]

    ...
</Location>

Note however that this will only work properly for / and /index.php requests to subdomains. You are much better off setting up separate document root directories for each subdomain if you intend to do anything more than this.



回答2:

Maybe you are interested in this.

http://httpd.apache.org/docs/2.2/mod/mod_vhost_alias.html#virtualdocumentroot

This allow, in Apache server, to automatically use a document root based in the subdomain



回答3:

I would use php to check the url. If it is a subdomain include index2.php else include index1.php

Without knowing the servers you are running on it is the only method I could think of.