end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

nginxでbasic認証

http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html

STEP0/2 - htpasswd コマンドのinstall

basic認証に使用するパスワードファイルを作成する為、apacheに付属する htpasswd をinstallします。

centosの場合

# yum install httpd-tools

debian , raspbian の場合

# apt-get install apache2-utils

STEP1/2 - パスワードファイルの作成

$ sudo /usr/bin/htpasswd -c /usr/local/nginx19/conf/auth_basic_passwd end0tknr
New password: 
Re-type new password:

STEP2/2 - nginx.conf の編集

以下のように auth_basic を auth_basic_user_file を追記して下さい。

# vi /usr/local/nginx19/conf/nginx.conf
http {
    :
    server {
        listen       80;
        server_name  raspi.end0tknr.mydns.jp;
        return 302 https://$host$request_uri;
    }

    server {
        :
        auth_basic "MEMBER ONLY";
        auth_basic_user_file "auth_basic_passwd";

        location / {
            root   html;
            index  index.html;
#            auth_basic "off";
        }
    }
}

上記の例では、location / {} 内に 「auth_basic "off"」がありますが、 このような設定で url / path 毎に 認証の要/不要を分けることも可能です。