ステージング用サーバのメンテナンスで、各アプリケーションに対してBasic認証を掛けたかったのですが、手順がスムーズに思い出せなかったのでメモ。
手順
1. パスワードファイル.htpasswd
の作成
対象のディレクティブのドキュメントルート上で、htpasswd
コマンドを実行します。
-bash-4.1$ htpasswd
Usage:
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.
-d Force CRYPT encryption of the password (default).
-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.
今回は新規でファイルを作成するので、以下のコマンドを実行。
-bash-4.1$ htpasswd -bc .htpasswd hoge hogepass
Adding password for user hoge
以下のようなファイルが生成されているはずです。
.htpasswd
hoge:GZ9xwU5haegLA
2. Apacheの設定
対象のVirtualHost
ディレクティブに対して、以下のように記述します。
hoge.conf
<VirtualHost *:80>
ServerName hoge.stage.unicast.ne.jp
DocumentRoot /home/admin/apps/hoge/current/public
PassengerEnabled on
<Directory />
AllowOverride all
Options -MultiViews
AuthType Basic
AuthUserFile /home/admin/apps/hoge/.htpasswd
AuthName "Authentication is required."
Require user hoge
</Directory>
</VirtualHost>
ちなみに、リバースプロキシの設定がされている場合は、以下のように設定します(ちょっとつまずきました)。
fuga.conf
<VirtualHost *:80>
ServerName fuga.stage.unicast.ne.jp
DocumentRoot /home/admin/apps/fuga/current/public
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
AuthType Basic
AuthUserFile /home/admin/apps/fuga/.htpasswd
AuthName "Authentication is required."
Require user fuga
</Proxy>
ProxyPass / http://localhost:4000/
ProxyPassReverse / http://localhost:4000/
</VirtualHost>