Is it possible to write an htpasswd file that redirects certain users to certain directories

.htaccessapache-2.2htpasswdredirection

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?

Best Answer

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]
Related Topic