Search code examples
apache.htaccessweb.htpasswd

How do I lock a folder with htaccess file?


I am trying to lock a folder on my site with htaccess file I created a htaccess file in the root and I created a htpasswd file inside the folder I want to lock But the problem is that it does not work and I am banned from entering the entire site until I delete the "Require valid-user" from the .htaccess file in order to allow me to enter the site.

htaccess file

ErrorDocument 404 /404.html
#Protect Directory
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /fares/.htpasswd
Require valid-user

htpasswd file

fares:djefaflia

It does not work on the local server or on the hosting


Solution

  • AuthUserFile /fares/.htpasswd
    

    The file-path provided to AuthUserFile should be an absolute filesystem path, not a root-relative URL-path (ie. it should not be relative to the document root) which is what this looks like. (Confusingly, a relative path is resolved relative to the ServerRoot, not the root of the filesystem.)

    The "absolute filesystem path" is the full file-path to the .htpasswd file on the server. For example, if the server path to your document root directory (where your HTML files are located) is /home/user/public_html and you are wanting to protect the directory /fares within your document root and you are storing the .htpasswd file inside that directory (although that is not recommended - see below) then the AuthUserFile directive should be like the following instead:

    AuthUserFile /home/user/public_html/fares/.htpasswd
    

    However, you should avoid storing the password file in the same directory you are protecting (for security reasons). Ideally, this file would be stored outside of the document root (ie. outside of the public HTML space). For example, you could mirror the file structure in a htpasswds directory above the document root in which you store all the relevant .htpasswd files on your system:

    AuthUserFile /home/user/htpasswds/fares/.htpasswd
    
    fares:djefaflia
    

    As written, this does not "look" correct (unless you are intentionally trying to store plain text passwords - which won't work on Linux). How are you generating the password file? You should be using a tool like htpasswd.exe (that comes with Apache), or something similar that generates a hash of the password. For example, it should look more like this:

    fares:$apr1$6Szn.sq3$7E6ZMJLBAZKWX.wmGRISu1