nginxでベーシック認証かける方法

テストサイトなどでは基本的にベーシック認証などを使ってアクセス制限かけることが多いと思います。apacheを使えばhtaccessで可能ですが残念ながらnginxはhtaccessを使えないのでconfファイルをいじって対応します

パッケージのインストール

nginx+apacheのリバースプロキシをしている場合は、既にパッケージが入っているかもしれませんが、nginx単体やnginx+nginxのリバースプロキシだとパッケージがないかもしれませんのでない場合はインストールします

[c] $ sudo yum install httpd-tools [/c]

.htpasswd ファイルの作成

[c] $ sudo htpasswd -c /etc/nginx/.htpasswd username New password: password Re-type new password: password Adding password for user username [/c]

confファイルに追記

[c] $sudo vi /etc/nginx/conf.d/default.conf server { listen 80; root /usr/share/nginx/html; index index.html index.htm; location / { auth_basic "Restricted"; # 認証時に表示されるメッセージ auth_basic_user_file /etc/nginx/.htpasswd; # .htpasswdファイルのパス } } [/c]

参考サイト

NginxでBasic認証させる件