Forum Moderators: phranque

Message Too Old, No Replies

Password Access for Directory Browsing

htaccess

         

Thadanator

10:45 pm on Dec 5, 2009 (gmt 0)

10+ Year Member



I simply want:

#1. to password protect directory browsing, but nothing else.
So if a user visits /images/old/ and there's no index.php, then they should get a login request.

#2. BUT if they view /images/new/ and there IS an index.php, it should let them view the index.php even though the request didn't imply index.php.

Now #2 might be more difficult.
I cannot believe google has failed me, it appears nobody has ever done this.

here is what i'm starting with in my .htaccess:


<FilesMatch "">
AuthType Basic
AuthUserFile ".htpasswd"
AuthName "Username and password required"
<Limit GET POST>
require user bob
require user guest
</Limit>
</FilesMatch>

So I've been trying to use <Filesmatch > to determine if it's a file or just a directory. But I suck at regular expressions.
Is there a better/easier way?

Thanks.

jdMorgan

3:59 pm on Dec 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Remember that <Files> and <FilesMatch> look at files, not URLs. That is, these directives are applied after the URL is resolved to a server filepath. This means that a <FilesMatch> on "" or "^$" will never ever match.

Further, these two directives only look at the filename, and not at any "directory path" to that file; The "directory path" matching is implicit in the fact that this code -- located in .htaccess in "this" directory, is running, since it won't run unless this .htaccess file's directory is being accessed by the request. So the pattern should and must be "^index\.php$"

However, your problem goes beyond that, in that <Files> and <FilesMatch> cannot check for "file exists." For that, you will need to use mod_rewrite with a RewriteCond testing %{REQUEST_FILENAME} for "-f" or "-s" and then use the [E=var:val flag on the RewriteRule to set a variable testable by "Allow from env=some-variable" and/or "Deny from env=some-variable".

Unfortunately, the fact that mod_auth usually runs before mod_rewrite may prove problematic here. But I'm thinking that the solution may involve setting "Require any", adding "Allow from env=some-variable, and then using mod_rewrite to set that variable if index.php exists.

An alternative is to use mod_rewrite as above, and then internally rewrite the request to a different "login-required" directory if index.php does not exist in the requested filepath. But I'm two cups of coffee short of a full tank here, and haven't thought this out completely -- mod_auth stuff always makes my head hurt anyway, regardless of caffeination level...

Anyway, maybe this will give you some ideas to experiment with.

Jim