weblog of key_amb

主にIT関連の技術メモ

(メモ) Nginx のアクセス制御と context の話 #nginx

Nginx 1.4 系を使っています。 Nginx で特定 IP のアクセスのみ許可する場合、次のような設定を書きます。

http {
    satisfy any;
    allow xxx.xxx.xxx.xxx; # 許可アドレス
    deny all;
}

ここで、許可アドレス以外は Basic 認証を入れたい場合、次のようにすればいいです。

http {
    satisfy any;
    allow xxx.xxx.xxx.xxx; # 許可アドレス
    auth_basic           'Login';
    auth_basic_user_file conf/htpasswd;
    deny all;
}

更に、特定の server ディレクティブ内では Basic 認証を入れたいが、それ以外では許可したくない、という場合は次のように書くことができます。

http {
    satisfy any;
    allow xxx.xxx.xxx.xxx; # 許可アドレス
    deny all;

    server {
        server_name foo.example.com;

        satisfy any;
        allow xxx.xxx.xxx.xxx; # 許可アドレス
        auth_basic           'Login';
        auth_basic_user_file conf/htpasswd;
        deny all;
    }

    server {
        server_name bar.example.com;
    }
    :
}

上記設定により、foo.example.com では「許可アドレスでは無認証、それ以外ではBasic認証でアクセス可能」となり、他では「許可アドレスのみ無認証でアクセス可能」となります。

つまり、http context の satisfy ~ deny までのブロックをまとめて server context で上書きできるようです。
直感的には、http context で "deny all" が付いているので、foo.example.com では Basic 認証でアクセスできなさそうですが、意外な結果でした。

参考