Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using the following RewriteRule to redirect wildcard sub domains to the corresponding folders in the /users sub-direcotry:

RewriteCond %{REQUEST_URI} !^/users/ [NC]
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$ [NC]
RewriteCond %1 !=www [NC]
RewriteRule ^(.*)$ /users/%1/$1/? [L]

I would like to prevent direct access to the users' folder by 301 redirecting to the sub domain version like this: =>

Any help would be greatly appreciated!

share|improve this question
up vote 2 down vote accepted

Since you're stopping the RewriteRule if there's a /users/ as the leading path, then would get them there, too - probably not as intended.

Consider changing your existing config for the per-user subdomains to a VirtualDocumentRoot in a wildcarded vhost instead of what's there, to cut down on complexity and reduce the number of regex evaluations needed per request.

<VirtualHost *:80>
    ServerAlias *
    VirtualDocumentRoot /dir/to/users/%1

Then, for the prevention of access to the /users/ directory structure through the normal hostname, apply this to just the main site's config:

RewriteRule ^/users/.*$ - [F]

If you're intent on keeping your existing handling of the subdomains with mod_rewrite, then you'll need to expand that to filter on hostname:

RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]   # I'm assuming?
RewriteRule ^/users/.*$ - [F]
share|improve this answer
Thank you Shane! Never thought of doing it through VirtualHost. – dSquared Sep 29 '11 at 23:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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