2024/02/13 22:13:39

nginx で BASIC認証

CentOS + nginx

CentOS + nginx の場合。

htpasswd のインストール

apache でおなじみの htpasswd コマンドをインストールする。

$ sudo yum install httpd-tools

apache 自体は httpd-tools パッケージに含まれないのでご安心を。なお、htpasswd 互換のツールがあれば全くそれで問題ない。

.htpasswd ファイル

.htpasswd ファイルの準備。

$ cd /usr/local/nginx/conf
$ sudo htpasswd -c .htpasswd USERNAME
New password:
Re-type new password:

nginx の conf編集

auth_basic ディレクティブと auth_basic_user_file ディレクティブで設定する。

location / {
    auth_basic           "closed site";
    auth_basic_user_file conf/.htpasswd;
}

http や server の Context でも有効なので、location より広い範囲で適用することもできる。

サイト内検索