HighND.com

Just another blog?

Password Protect a Linux Directory Using Command Line and Htaccess

Do you want to protect your Linux folders and files from public internet access without using an online password generator? This article will show you how to add basic authentication on folders using only command line and .htaccess file in 2 simple steps:

  1. First step you need to generate the username and password. Credentials will be saved in a .htpasswd file that should be placed outside the public directory for security reasons. My public directory is /var/www/html so I am generating the password file in /var/www:
    sudo htpasswd -bc /var/www/.htpasswd admin strongPassword

    This command will create a new file .htpasswd in /var/www and add the username admin with password ‘strongPassword’ encrypted in the file.
    -b option will use batch mode and read the password from the command line, remove this option if you don’t want the password to be clearly visible on the command line.
    -c option will create the file if it doesn’t exist and overwrite it if it already exist. Remove this option if you are adding a new user but you don’t want to remove the old one.

  2. In second step, you need to create the .htaccess file inside the directory that you need to protect and refer to the password file.
    Create .htaccess file with your favorite editor and add the following lines:

    AuthUserFile "/var/www/.htpasswd"
    AuthType Basic
    AuthName "Password Protected Directory"
    require valid-user
    

    AuthUserFile indicates the path of the password file we created in step1
    AuthName is the message that will appear when someone visit the protected directory

 

 

 

 

, , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*


− 1 = five

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>