Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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!

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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
</VirtualHost>

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
add comment

Your Answer

 
discard

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.