Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess password protect files with different users

I have a files server and I use mod_autoindex to server the files. I have a username and password in htaccess so only certain people can access the files. I have added another user to htpasswd but I would only like that user to access some of the files/folders.

Here is my htaccess file now:

AuthType Basic
AuthName "restricted"
AuthUserFile E:\\path\\to\\.htpasswd

<Files "filesForAnyUser\\*">
  Require valid-user
</Files>

<Files "*">
Require user admin
</Files>

I'm sure I am doing something wrong but I can't find any good documentation on this.

like image 975
Tony Brix Avatar asked Sep 26 '13 19:09

Tony Brix


2 Answers

If you have a folder called "filesForAnyUser" and a folder where you have files only for admin, you need to make 2 htaccess files. One in "filesForAnyUser":

AuthType Basic
AuthName "restricted"
AuthUserFile E:\\path\\to\\.htpasswd
Require valid-user

And one in the other directory:

AuthType Basic
AuthName "restricted"
AuthUserFile E:\\path\\to\\.htpasswd
Require user admin
like image 90
Jon Lin Avatar answered Oct 24 '22 19:10

Jon Lin


So here is my final solution for anyone else.

Put the following in the root folder:

AuthType Basic
AuthName "restricted"
AuthUserFile E:\\path\\to\\.htpasswd
Require user admin

Put the following in any folder where admin and user1 can access the file:

AuthType Basic
AuthName "restricted"
AuthUserFile E:\\path\\to\\.htpasswd
Require user admin user1 #users separated by space or "Require valid-user" if all users

If you want to allow user1 to only access certain files you can use <FilesMatch>:

AuthType Basic
AuthName "restricted"
AuthUserFile E:\\path\\to\\.htpasswd
Require user admin
<FilesMatch "^(doc1.pdf|doc2.txt|doc3.docx)$">
  Require user admin user1 #or valid-user
</FilesMatch>

This gives admin access to all files in that folder but user1 only access to the files listed in <FilesMatch>

Note: The files in <FilesMatch> are for the current directory and any sub directory. I'm not sure how to limit it to only the current directory.

like image 34
Tony Brix Avatar answered Oct 24 '22 17:10

Tony Brix