LoginSignup
11
8

More than 3 years have passed since last update.

nginxでBASIC認証をかけてみる

Posted at

概要

さくらVPSでWebアプリケーション開発をしようかと準備しておりまして、
誰でもアクセスできる状態だと困るな〜ということで、BASIC認証をかけることにしました。

BASIC認証の設定

BASIC認証をかけるには、htpasswdコマンドで.htpasswdファイルを作成する必要があります。
なので、まずはそのコマンドが使えるようにhttpd-toolsをインストールします。

# yum -y install httpd-tools

次に、以下のコマンドを実行して.htpasswdファイルを作成します。
一応、今回はnginxを利用するため、nginxっぽいディレクトリ内にファイルを配置します。

# htpasswd -c -b /etc/nginx/.htpasswd {username} {password}

最後にnginxの設定ファイルに上記で作成した.htpasswdファイルを利用するBASIC認証の設定を追加して、
nginxのサービスを再起動すればBASIC認証の設定が完了です。

/etc/nginx/conf.d/default.conf
    location / {
      # 指定された順序でfileやdirの存在を確認し、最初に見つかったものを返却する。
      # いずれも無かった場合は、最後に指定されたパスに遷移する。
      try_files $uri $uri/ /index.php$is_args$args;

      # 以下2行の設定を追加します。
      auth_basic "Restricted";
      auth_basic_user_file /etc/nginx/.htpasswd;
    }

サイトにアクセスするとBASIC認証がかかっていることが確認できます。

スクリーンショット 2020-10-04 7.05.48.png

11
8
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
11
8