Friday, March 14, 2008

How do I put a password on my web pages?

You will need to create two files, .htpasswd and .htaccess. The .htaccess file defines what is permitted. The .htpasswd file contains the usernames and encrypted passwords for those users. For example, if I have a server that is www.example.com and it's DocumentRoot is /home/vhost/example.com/html and I have a directory inside that called /protected I will need to set up .htaccess like this:

AuthUserFile /home/vhost/example.com/html/protected/.htpasswd
AuthType Basic
AuthName "Whatever I want to call this text descriptor"

require valid-user

This now defines what the password file is called, what kind of authentication I'm doing (Basic) and what I'm restricting (GET and POST operations). Now to create the .htpasswd file all you have to do is log into the server via ssh and run this command:

htpasswd -c /home/vhost/example.com/html/protected/.htpasswd

This will create the file. You only want to do this once. If you do it again it will delete the file and create a new one with only the entry you're creating. All the previous entries will have been deleted. For subsequent new users you will run the command without the -c switch:

htpasswd /home/vhost/example.com/html/protected/.htpasswd

No comments: