Nginx Basic認証設定方法

Module ngx_http_auth_basic_module
公式ドキュメントの通りにやればよいので簡単。問題があるとすればauth_basic_user_fileの生成方法かな。

たまたまDigitalOceanの記事を見つけたので眺めてみた。
How To Set Up HTTP Authentication With Nginx On Ubuntu 12.10 | DigitalOcean

Step 1: Apache Utils

We need htpasswd to create and generate an encrypted for the user using Basic Authentication. Install apache2-utils using the command below.

  sudo apt-get install apache2-utils
How To Set Up HTTP Authentication With Nginx On Ubuntu 12.10 | DigitalOcean

htpasswdコマンドを使うためにapache2-utilsをインストールしているんだけどその為だけにapache関連の物入れるのもなあ。

そんなこともあろうかとNginx公式ドキュメントに回答がある。
Frequently Asked Questions | NGINX

How do I generate an .htpasswd file without having Apache tools installed?

In Linux (and other Posix): given users John, Mary, Jane and Jim and passwords V3Ry, SEcRe7, V3RySEcRe7 and SEcRe7PwD, in order to generate a password file named .htpasswd, you would issue:

printf "John:$(openssl passwd -crypt V3Ry)\n" >> .htpasswd # this example uses crypt encryption
printf "Mary:$(openssl passwd -apr1 SEcRe7)\n" >> .htpasswd # this example uses apr1 (Apache MD5) encryption
printf "Jane:$(openssl passwd -1 V3RySEcRe7)\n" >> .htpasswd # this example uses MD5 encryption
(PASSWORD="SEcRe7PwD";SALT="$(openssl rand -base64 3)";SHA1=$(printf "$PASSWORD$SALT" | openssl dgst -binary -sha1 | \
sed 's#$#'"$SALT"'#' | base64);printf "Jim:{SSHA}$SHA1\n" >> .htpasswd) # this example uses SSHA encryption
Frequently Asked Questions | NGINX

いくつかフォーマットがある。注意すべきなのはcryptフォーマットだと8文字以上のパスワードに対応していなくて、MD5なら対応しているということ。
htpasswdのマニュアルにその辺のことが書いてあるので目を通すとよさそう。
htpasswd - Manage user files for basic authentication - Apache HTTP Server Version 2.2