Dave's Brain

Browse - Computer Tips - How can I password protect part of a website using an .htaccess file?

Date: 2014nov21
Product: Apache

Q.  How can I password protect part of a website using an .htaccess file?

A.  First make sure .htaccess files are enabled in your Apache configuration.
On a Linux system this will be somewhere like
/etc/httpd/conf.d/default.conf

<Directory /htdocs> AllowOverride all </Directory>
This means in folder /htdocs and below .htaccess files will be read and obeyed. The module needs to be loaded too. But it is by default. And there is an Apache directive to stop web users from viewing files that begin with ".ht" but that is also enabled by default. In the folder you want to protect make a file called .htaccess containing:
AuthUserFile /etc/httpd/conf/htpasswd AuthGroupFile /dev/null AuthName priv AuthType Basic <LIMIT GET POST> require user myuser </LIMIT>
It doesn't have to be exactly this way but this gets you going. The says only user myuser with the correct password from /etc/httpd/conf/htpasswd is allowed in. I am not putting a dot in front of htpasswd because there is no need to hide it since its out of the website. Use the htpasswd command to make that file:
htpasswd -c /etc/httpd/conf/htpasswd myuser
You will be prompted for the password. Restart Apache and test it. There are other ways, besides using an .htaccess file.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.