0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

概要

webarenaでubuntu18.04やってみた。
vpsクラウドが終了するらしい。
vpsクラウドからindigoに引っ越す検討。
indigo申し込んでみた。
ApacheでBasic認証を計画。

ApacheでBasic認証

ApacheでBasic認証(基本認証)を設定するには、「パスワードファイルの作成」と「設定ファイル(または.htaccess)の編集」の2ステップが必要です。

以下に、最短で設定を完了するための手順をまとめました。

Step 1. パスワードファイル(.htpasswd)の作成

まずは、認証に使用するユーザー名とパスワードを保存するファイルを作成します。セキュリティ確保のため、ブラウザから直接アクセスできないディレクトリ(/etc/httpd/ や /etc/apache2/ など)に配置するのが一般的です。

ターミナルで以下のコマンドを実行します。

# 初めてファイルを作成する場合(-c オプションを付ける)
sudo htpasswd -c /etc/httpd/conf/.htpasswd ユーザー名

# 2人目以降のユーザーを追加する場合(-c は不要)
sudo htpasswd /etc/httpd/conf/.htpasswd 追加するユーザー名

※コマンドを実行すると、パスワードの入力を求められます。
※OSや環境によってパスワードファイルの保存先(/etc/apache2/.htpasswd など)は適宜変更してください。

Step 2. Apacheの設定(2つの方法)

ディレクトリに対して認証をかける方法は、「Apacheの主要設定ファイルに直接書く方法」と、「設定したいディレクトリに .htaccess を置く方法」の2種類あります。

パターンA:設定ファイル(httpd.conf など)に直接記述する

サーバー全体の管理権限がある場合は、動作が高速なこちらの方法が推奨されます。
/etc/httpd/conf/httpd.conf や /etc/httpd/conf.d/basic-auth.conf などの設定ファイルに以下を追記します。

<Directory "/var/www/html/target-dir">
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/httpd/conf/.htpasswd
    Require valid-user
</Directory>

パターンB:.htaccess ファイルを使用する

レンタルサーバーなどで主要設定ファイルを触れない場合は、制限をかけたいディレクトリの直下に .htaccess という名前のファイルを作成し、以下を記述します。

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/httpd/conf/.htpasswd
Require valid-user

※ .htaccess を利用する場合、主要設定ファイル(httpd.conf)側でそのディレクトリに対して AllowOverride AuthConfig(または AllowOverride All)が許可されている必要があります。

ディレクティブの解説

• AuthType Basic:
Basic認証を使用することを指定します。
• AuthName "...":
認証画面のダイアログに表示される文字列(領域名)です。任意の英数字を入力します。
• AuthUserFile:
先ほど htpasswd コマンドで作ったパスワードファイルの絶対パスを指定します。
• Require valid-user:
パスワードファイルに登録されているすべてのユーザーにアクセスを許可します(特定のユーザーのみに絞る場合は Require user ユーザー名 と書きます)。

Step 3. 設定の反映

設定ファイルを書き換えた後は、設定に構文エラーがないか確認し、Apacheを再起動(またはリロード)して設定を反映させます。

# 設定ファイルの構文チェック
sudo apachectl configtest

# Apacheの再起動(CentOS/RHEL/Rocky Linux系)
sudo systemctl restart httpd

# Apacheの再起動(Ubuntu/Debian系)
sudo systemctl restart apache2

設定したURLにブラウザでアクセスし、ログインダイアログが表示されれば成功です。

以上。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?