Dynamic virtual hosts

Problems:

You want to have each user on your system automatically have username.domain.com mapped to their home directory.

Recipe:

RewriteEngine On
# Skip www.domain.com
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com
RewriteRule ^/(.*)$  /home/%1/www/$1 [L]

Discussion:

The first RewriteCond skips requests for content from www.domain.com, which we want to be handled via the regular mechanism. It may also be useful to exclude other hostnames which you don't want to get mapped to home directories.

The second RewriteCond exists to capture which hostname was requested. When matches are captured (by using parentheses) in a RewriteCond, the captured pattern goes into the variables %1, %2, %3, and so on. In this case, a request for a hostname of username.domain.com will result in %1 being set to username.

Finally, our RewriteRule captures the entire requested URL, and causes it to be served out of that user's home directory. For example, a request for http://rbowen.domain.com/foo/bar.html will result in the file /home/rbowen/www/foo/bar.html being served.

It is important to note that you will still need to make the necessary changes to your DNS server to make these hostnames work. Generally, this would be done by creating a wildcard DNS entry mapping *.domain.com to this server. You will need to consult the documentation for your particular DNS server as to how to accomplish this.

  • No labels