Password protect a folder with .htaccess

Sometimes it’s useful to have a folder of your website-content password protected.
This can easily be achieved by adding a simple rule to your htaccess-file when using Apache (you can convert your apache .htaccess-file to nginx instructions for example [].
You should place the file in the folder you want to protect.
To create a user and a password you run htpasswd from your terminal like:

htpasswd -c .htpasswd user

This will respond with:

New password:
Re-type new password:
Adding password for user user

Now you can add this rule to your htaccess-file:

AuthType Basic
AuthName "Password Protected"
AuthUserFile /path/to/your/.htpasswd
Require valid-user

That’s it:)

For more info try:

$ htpasswd --help
htpasswd [-cmdpsD] passwordfile username
htpasswd -b[cmdpsD] passwordfile username password

htpasswd -n[mdps] username
htpasswd -nb[mdps] username password
-c Create a new file.
-n Don't update file; display results on stdout.
-m Force MD5 encryption of the password (default).
-d Force CRYPT encryption of the password.
-p Do not encrypt the password (plaintext).
-s Force SHA encryption of the password.
-b Use the password from the command line rather than prompting for it.
-D Delete the specified user.
On other systems than Windows, NetWare and TPF the '-p' flag will probably not work.
The SHA algorithm does not use a salt and is less secure than the MD5 algorithm.

And keep in mind that if you run
htpasswd [options] [pw-file] [username] [password]
your password will probably be saved in your history-file (eg. if you use bash).