« Arduino Controlled LED Staff | Home | Google+, I hardly knew (anybody on) you... »

June 14, 2011

Restricting apache paths, per user, with mod_rewrite

This took long enough to track down that it warranted documenting for the rest of the internet. Many thanks to maze.io for being the only other place on the internet describing this behavior.

Sometimes you want to restrict a URI by user, such that a logged in user can only view the contents of their own directory. If you place the following .htaccess in the parent directory of the <username> directory, you can lock <username>s to their own directories (require valid-user, and then):

RewriteEngine On
RewriteCond %{REMOTE_USER} ^(.+)
RewriteCond %1:$1 !^([^:]+):\1$
RewriteRule ^([^/]+)/ - [F,L]

This works by capturing the requested directory (line 4) and appending it to the RewriteCond on line 3 as $1. REMOTE_USER is prepended to the test string of line 3 so it can be pulled back out in the cond pattern on line 3 and compared to the requested directory.

So if REMOTE_USER = heph, and the requested file is /ted/secretfile.txt, here is the process (out of order, for clarity. A common statement in reference to mod_rewrite):

RewriteCond %{REMOTE_USER} ^(.+) # Sets %1 = heph
...
RewriteRule ^([^/]+)/ - [F,L] # Sets $1 = ted
...
RewriteCond %1:$1 !^([^:]+):\1$ # Means RewriteCond heph:ted !heph:heph$

This RewriteCond matches (negative match, notice the !), so follow through with the RewriteRule, return Forbidden, and block the unauthorized Heph from accessing Ted's directory.

About this Entry

This page contains a single entry by Hephaestus published on June 14, 2011 4:30 PM.

Arduino Controlled LED Staff was the previous entry in this blog.

Google+, I hardly knew (anybody on) you... is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.