zuntan02のはてなブログ

備忘録的なものです。時々職場の技術者ブログにも転記してますが、メインはこちらで。

nginxでのベーシック認証のかけかた

nginxでのベーシック認証のかけかた
参考:
qiita.com

.htpasswd ファイルの作成

# htpasswdコマンドが必要

yum install httpd-tools

ユーザ名とパスワードを追加。

(初回)htpasswd -c /etc/nginx/.htpasswd username
→2回目以降は-cを外さないと.htpasswdが上書きされるので注意
(2回目以降)htpasswd /etc/nginx/.htpasswd username

nginxの設定ファイルの追記

.htpasswd ファイルを読み込み、Basic 認証を適用。
/etc/nginx/nginx.conf

server {
    listen 80;
    root /usr/share/nginx/html;
    index index.html index.htm;

    auth_basic "Restricted";                   # 認証時に表示されるメッセージ
    auth_basic_user_file /etc/nginx/.htpasswd; # .htpasswdファイルのパス
}
特定のIPにはBasic認証を行わない場合

【参考】
http://d.hatena.ne.jp/podhmo/20110311/1299817584

server {
    listen 80;
    root /usr/share/nginx/html;
    index index.html index.htm;

    # add Basic Auth
    satisfy any;
    allow 許可IP1;
    allow 許可IP2;
    deny all;

    auth_basic "Restricted";                   # 認証時に表示されるメッセージ
    auth_basic_user_file /etc/nginx/.htpasswd; # .htpasswdファイルのパス
}


または

特定のIPにはBasic認証を行わない場合(CloudFront+ELB配下)
server {
    listen 80;
    root /usr/share/nginx/html;
    index index.html index.htm;

    # Auth Basic
    auth_basic_user_file /etc/nginx/.htpasswd; # .htpasswdファイルのパス

    set $allow 0;
    if ( $http_x_forwarded_for ~ 111\.111\.111\.111 ){ set $allow 1; }
    if ( $http_x_forwarded_for ~ 111\.111\.111\.112 ){ set $allow 1; }
    if ( $http_user_agent = "ELB-HealthChecker/2.0" ) { set $allow 1; }  #上位TGなどからのヘルスチェックはパスするようにする 

    if ( $allow = 1) {
        set $auth_basic off; #Basic認証off
    }

    if ($allow = "0"){
        set $auth_basic "Restricted";          # 認証時に表示されるメッセージ
    }
    
    auth_basic $auth_basic;
    }

反映

service nginx configtest
service nginx reload