On Apache 2.2.x I've activated mod_userdir. I used the default setup, so that http://localhost/~name/ will be connect with ~name/public_html/ and a path within public_html, e.g. ~name/public_html/mySite can be reached through http://localhost/~name/mySite.

How can I achieve, that the same path can be reached through http://mySite.name.localhost/? I don't want a manual approach like it is suggested in other SF questions (such as Apache: Setting up local test server with subdomains), but rather want an automatic mapping of all available paths to the corresponding URL.

I think, several steps will need to be taken: Change mod_userdir configuration, so that the subdomain of localhost will be connected with all available user names on the machine. The second step would maybe include the usage of mod_rewrite, so that the subsubdomain could be matched to the path within ~name/public_html...

What would be your prefered way?


The solution is flagged. I some small modifications to meet special requirements and added comments:

RewriteEngine on
# check, if not redirected yet
# look for URLS like 'subdir.username.localhost'
RewriteCond %{HTTP_HOST} (.+)\.([^.]+)\.localhost$
# check if /home/username/public_html/subdir is a directory or symbolic link
RewriteCond /home/%2/public_html/%1 -d [OR]
RewriteCond /home/%2/public_html/%1 -l
# rewrite to default target
RewriteRule ^(.+) %{HTTP_HOST}$1 [C]
# rewrite to /home/username/public_html/subdir
RewriteRule (.+)\.([^.]+)\.localhost(?::\d+)?(.*) /home/$2/public_html/$1$3 [L]

I had a similar need a few weeks ago. I solved it using mod_rewrite, by putting this in my default vhost definition:

RewriteEngine on
 # look for URLS like 'subdir.username.localhost'
 RewriteCond %{ENV:REDIRECT_STATUS} ^$
 RewriteCond %{HTTP_HOST} ([^.]+)\.([^.]+)\.localhost$
 RewriteCond /home/%2/public_html/%1 -d
 RewriteRule ^(.+) %{HTTP_HOST}$1 [C]
 RewriteRule ([^.]+)\.([^.]+)\.localhost(?::\d+)?(.*) /home/$2/public_html/$1$3 [L]

There is some more info at https://gist.github.com/744971, including getting username.localhost to resolve to /home/username/public_html

  • Since some of my 'subdirs' contain dots, I rewrote parts of the regex. Also some paths are symbolic links, so I added another RewriteCondition. Since your solution does exactly what I asked for, I flaged it as the solution but will add my changes to the initial question. Great work! – MaoPU Jan 5 '11 at 7:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.