Take the 2-minute tour ×

Assuming that I have a domain, say, mydomain.com and three directories under it call them dir1, dir2 and dir3, then is it possible to put an htpasswd file at the web root and have it redirect authenticated users to their respective directories (e.g. user joecorleone101 always get redirected to dir3 upon being authenticated.)?

First of all I want to know if this is possible and second is it safe or practical (or impractical)? Am I thinking about it the wrong way? Should I maybe use an htaccess file?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Apache mod_rewrite is your friend, it can use HTTP headers.

RewriteEngine On
RewriteCond %{REMOTE_USER} ^joecorleone101$
RewriteRule .* dir3/ [R,L]
  • If HTTP REMOTE_USER equals joecorleone101 use the rewrite rule
  • Match against everything (.*)
  • Rewrite url to dir3
  • [R] is redirect
  • [L] stop rewriting

You can also use the REMOTE_USER in the substition part:

RewriteCond %{REMOTE_USER} ^.*$
RewriteRule .* %{REMOTE_USER}/ [R,L]
  • If REMOTE_USER is filled (^.*$) use the rewrite rule
  • Match against everything (.*)
  • Rewrite url to the value in REMOTE_USER
  • [R] is redirect
  • [L] stop rewriting

This also works from .htaccess but has some behavior differences, the directory is removed in the pattern matching and added in the substitution part.

To use the value matched in the RewriteCond you can use the %N (1 <= N <= 9).

RewriteCond %{REMOTE_USER} (\d{3})$
RewriteRule .* http://www.example.com/%1 [R,L]
  • Match against users who's name end with 3 digits (\d{3})$
  • Match against any given url (.*)
  • Rewrite it to http://www.example.com/123 (if user ends with 123)
  • Redirect and stop rewriting [R,L]
share|improve this answer
Thanks for the response. It pointed me in the right direction –  user41157 May 3 '10 at 23:41
Say, I want to write this rule by I just can't quite get it right: #RewriteCond %{LA-U:REMOTE_USER} (\d{3})$ #RewriteRule !^%1 clients.randomtype.ca/%1 [R,L]. This is what I mean to say: "If the REMOTE_USER has a user name ending in 3 digits then capture the three digits that match and 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. (I'm doing this in an .htaccess file by the way). I think it is the the first instance of '%1' that is not right. Any tips? –  user41157 May 4 '10 at 0:00
The problem is probably the LA-U, this is only necessary when you're not in a .htaccess file. Your pattern !^%1 will cause the rewrite rule to fire when your URL does not start with the digits in the user name. –  basvdlei May 4 '10 at 15:16
Oh I see, thank you very much for your help. I really appreciate it. –  user41157 May 4 '10 at 16:34

Your Answer


