NGINXでBasic認証を設定する
RHEL8・NginxでBasic認証を設定する方法を色々調べてみた。
必要なパッケージのインストール
# dnf install httpd-tools
htpasswdコマンドでファイルを作成
(初回)htpasswd -c /etc/nginx/conf.d/.htpasswd username
(2回目以降)htpasswd /etc/nginx/conf.d/.htpasswd username
※2回目以降は-cを外さないと.htpasswdが上書きされるので注意
# htpasswd -c /etc/nginx/conf.d/.htpasswd [username]
New password: [パスワードを入力]
Re-type new password: [パスワードを入力]
Adding password for user username
.htpasswdファイル確認
# cat /etc/nginx/conf.d/.htpasswd
abcde:$apr1$4kDGxg/l$LRPjH55Q1SUD9YQw/vRWw.
プロジェクト全体にBasic認証 (nginx.conf)
server {
--- 省略 ---
location / {
auth_basic "Restricted"; # 認証時に表示されるメッセージ
auth_basic_user_file /etc/nginx/conf.d/.htpasswd; # .htpasswdファイルのパス
}
}
特定IPアドレスにベーシック認証を除外
server {
--- 省略 ---
location /
auth_basic "Restricted"; # 認証時に表示されるメッセージ
auth_basic_user_file /etc/nginx/conf.d/.htpasswd; # .htpasswdファイルのパス
satisfy any;
allow 許可するIP;
allow 許可するIP;
deny all;
}
}
指定したディレクトリ配下にBasic認証
location /xxxxx/ {
root /var/www/html/<ドメイン名>;
index index.html index.htm index.php;;y
auth_basic "Basic Authentication";
auth_basic_user_file /etc/nginx/conf.d/.htpasswd;
}
設定ファイルの整合性を確認
# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
再起動
# systemctl reload nginx
注意:SSLで利用するように!
Basic認証のダイアログで入力されたユーザー名とパスワードは、デコードすれば簡単にパスワードが見られてしまうため、非SSLのWebサーバーでは利用しないようにする。
参考サイト
https://reigle.info/entry/2022/08/17/100000
https://rin-ka.net/nginx-basic-auth
https://marketing-web.hatenablog.com/entry/nginx_basic

