htaccess password protect files with different users
Asked Answered
I

2

5

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.

Insoluble answered 26/9, 2013 at 19:31 Comment(3)
What is "filesForAnyUser"? Is that a folder?Bossism
ya that is a folder with files that should be available to any userInsoluble
E:\\path\\to\\.htpasswd consider changing it to E:/path/to/.htpasswd using the opposite slash will save you some trouble in some specific situations.Testator
B
5

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
Bossism answered 26/9, 2013 at 20:30 Comment(2)
that worked but why doesn't the <Directory> or <Files> directives work?Insoluble
@UziTech Both Directory and Location have contexts of "server" and "virtualhost" config. Not "htaccess", so those directives can't be used in an htaccess file, which makes sense because putting an htaccess file in a directory is kind of like using a <Directory> on that directory.Bossism
I
3

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.

Insoluble answered 28/9, 2013 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.