Sign up ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

This is what I have so far but I can't get the RewriteCond and RewriteRule properly.

RewriteEngine On

RewriteCond %{LA-U:REMOTE_USER} (\d{3})$ 
RewriteRule !^%1 [R,L].

AuthName "My Domain Protected Area"
AuthType Basic
AuthUserFile /path/to/my/.htpasswd
Require valid-user

This is what I mean the ReWriteCond and RewriteRule to say:

"If the REMOTE_USER has a username ending in 3 digits then capture the three digits that match and for whatever url they are trying to access if it does not start with the 3 digits captured then redirect them to the sub directory with the name equal to those captured three digits."

In other words, if a user named 'johnny202' is authenticated then if he's requesting any directory other than then he should be redirected to

The only thing I can think of that is wrong is the first instance of '%1'.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Something to remember with mod_rewrite - it matches the rule before looking at the conditions, so at the time it checks the rule pattern, it hasn't run any of the conditions, and hasn't set up the %1 backreference yet. I'd try separating the URL check into a second condition - something like the following

RewriteCond %{REMOTE_USER} ([0-9]{3})$
RewriteCond %{REQUEST_URI} !^/%1
RewriteRule ^.*$ [R,L].

This way, the rule will match every request, so the conditions will always be examined, but the redirect should only happen where the request doesn't begin with the "correct" number.

N.b. I've taken out the LA-U in the first condition - as I understand it, you don't need that if it's in a .htaccess file (only if the rewrite is in the main Apache config).

share|improve this answer
N.b. I haven't tested this, so you may need to play with it a bit to get it working. – meulop May 4 '10 at 12:36
I didn't know it matches the rule before looking at the condition. This explains so much. Thanks for your help. I really appreciate it. – user41157 May 4 '10 at 16:36
No problem - it confused me for a while until I set RewriteLogLevel to something fairly high to really see what was going on (which of course you can't do in a .htaccess file) – meulop May 4 '10 at 19:15

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.