Nginxでベーシック認証をかける

Nginxでベーシック認証をかける

Nginx でベーシック認証をかける手順をまとめました。
サーバ環境は、GCP、Bitnamiのマシンイメージでの対応履歴です。

実行環境

  • Google Cloud Platform
  • WordPress with NGINX and SSL Certified by Bitnami and Automattic 5.4.2-3
  • Nginx

htpasswdファイル作成

htpasswdファイルを作成します。

sudo htpasswd -c -b /home/danroo/apps/wordpress/.htpasswd [ユーザ名] [パスワード]

Nginx設定変更

以下のファイルを編集する

$ pwd
/opt/bitnami/nginx/conf/bitnami
$ vi bitnami.conf

追記した箇所は、4箇所のみ

    # HTTP server

    server {
        listen       80;
        server_name  localhost;
        return 301 http://danroo.com$request_uri; # ← 追記箇所① httpsに切り替える

        #include "/opt/bitnami/nginx/conf/bitnami/phpfastcgi.conf";

        include "/opt/bitnami/nginx/conf/bitnami/bitnami-apps-prefix.conf";
    }

    # HTTPS server

    server {
       listen       443 ssl;
       server_name  localhost;
       if ($host != "www.danroo.com") { # ← 追記箇所② www付きURLに切り替える
         return 301 http://danroo.com$request_uri;
       } # ← ここまで

       ssl_certificate      server.crt;
       ssl_certificate_key  server.key;

       ssl_session_cache    shared:SSL:1m;
       ssl_session_timeout  5m;

       ssl_ciphers  HIGH:!aNULL:!MD5;
       ssl_prefer_server_ciphers  on;

       auth_basic "Restricted"; # ← 追記箇所③  ベーシック認証を設定
       auth_basic_user_file /home/nonoichi123/apps/wordpress/.htpasswd; # ← 追記箇所④  ベーシック認証のパスワードをファイルを指定
       location / {
         index index.php index.html index.htm;
         try_files $uri $uri/ /index.php?$args;
       }

       #include "/opt/bitnami/nginx/conf/bitnami/phpfastcgi.conf";

       include "/opt/bitnami/nginx/conf/bitnami/bitnami-apps-prefix.conf";
    }

    include "/opt/bitnami/nginx/conf/bitnami/bitnami-apps-vhosts.conf";

# Status
server {
    listen 80;
    server_name local-stackdriver-agent.stackdriver.com;
    location /nginx_status {
      stub_status on;
      access_log   off;
      allow 127.0.0.1;
      deny all;
    }
    location / {
      root /dev/null;
    }
}

Nginx 再起動

再起動後、ブラウザからアクセスし、ベーシック認証が表示されることを確認する

$ sudo /opt/bitnami/ctlscript.sh restart nginx

参考リンク

サーバ・インフラカテゴリの最新記事