LoginSignup
3
4

More than 5 years have passed since last update.

リバースプロキシサーバとして使ってるNginxでBasic認証をかける(サブドメイン対応)

Posted at

VPSを借りてWEBサービスを個人開発しているが、開発用のサブドメインを用意したりするときに、Basic認証を掛けたいと思ったのでその時のメモ。

今回はASP.NET Coreで作ったアプリに対するリバースプロキシとしてNginxを使っている。

OSはUbuntuの16.04か18.04(忘れた)

htpasswdインストール

sudo apt-get install apache2-utils

htpasswdファイルの作成

# 認証に使うユーザ名とパスワードを入力する
sudo htpasswd -c /etc/nginx/.htpasswd {username}
 ->New password: {password}
 ->Re-type new password: {password}

nginx設定ファイルに追記


server{
    server_name    example.com;

    #(略)

    location / {
        auth_basic "認証時のメッセージ";
        auth_basic_user_file /etc/nginx/.htpasswd; # .htpasswdファイルのパス
        proxy_pass    http://localhost:25000/; #リバースプロキシの先
    }

}

#こちらはサブドメインとしてsub.example.comにも認証をかけたい場合の設定
server{
    server_name    sub.example.com;

    # (略)

    location / {
        auth_basic "認証時のメッセージ";
        auth_basic_user_file /etc/nginx/.htpasswd; # .htpasswdファイルのパス
        proxy_pass    http://localhost:15000/;
    }

}

nginx再起動

 sudo systemctl restart nginx

これでサブドメインごとにbasic認証をかけたりかけなかったりできるので、個人開発等で開発用のサブドメインに認証かけたい時とか便利

3
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
3
4