search by tags

for the user

adventures into the land of the command line

basic auth in apache

sometimes im working on something and i want to hide a page because i haven’t finished yet. a very very simple way to prevent people from looking inside is to protect the page with basic auth. this can be easily broken through, but it’s more of a deterent. it’s also useful for sites that are hosted on company intranets, to give certain teams or people access to certain tools or monitoring applications

so lets assume we already have apache installed and running, and it is serving files and webpages/apps or whatever. you have a site you want to protect with basic auth

create an apache password file and set permissions

$ sudo mkdir /etc/htpasswd/
$ sudo chown apache:apache /etc/htpasswd/
$ sudo chmod 500 /etc/htpasswd/
$ sudo htpasswd -c /etc/htpasswd/.htpasswd user
$ sudo chown apache:apache /etc/htpasswd/.htpasswd
$ sudo chmod 400 /etc/htpasswd/.htpasswd

the htpasswd -c command creates a .htpasswd file with a user inside. you will be prompted for a password for the user after entering this command. if you want to add additional users, do the same again but drop the -c option

$ sudo htpasswd /etc/htpasswd/.htpasswd anotheruser

to configure the server to know who is allowed from the htpasswd file, put the below into the tags in the httpd.conf file for the web root and/or cgi-dir root of your website/app

$ vim /etc/httpd/conf/httpd.conf

<Directory "/var/www/html/">
#
# Controls who can get stuff from this server.
#
 AuthType Basic
 AuthName "Authentication Required"
 AuthUserFile "/etc/htpasswd/.htpasswd"
 Require valid-user
</Directory>


#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
 AllowOverride None
 Options None

 AuthType Basic
 AuthName "Authentication Required"
 AuthUserFile "/etc/htpasswd/.htpasswd"
 Require valid-user

 AddHandler default-handler .html .htm
</Directory>

now if you try to access any file in the path from the webroot, it’ll prompt you for basic auth, granting access to user(s) in the htpasswd file