LoginSignup
7
4

More than 5 years have passed since last update.

VirtualHostで区切られたアプリケーションに対して個別にBasic認証をかける

Posted at

ステージング用サーバのメンテナンスで、各アプリケーションに対して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>

参考URL

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4