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:

www.domain.com/users/username/sub1/sub2/ => username.domain.com/sub1/sub2/

Any help would be greatly appreciated!


Since you're stopping the RewriteRule if there's a /users/ as the leading path, then username.domain.com/users/username/sub1/sub2/ 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>
    ServerName usernames.domain.com
    ServerAlias *.domain.com
    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]
  • Thank you Shane! Never thought of doing it through VirtualHost. – dSquared Sep 29 '11 at 23:35

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.