LoginSignup
2
2

More than 5 years have passed since last update.

Basic認証とIP制限を設定して、Nginxサーバーのセキュリティを高める

Last updated at Posted at 2018-07-18

動作環境

~
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.4 LTS"
$ nginx -v
nginx version: nginx/1.14.0

Basic認証の設定

Basic認証はもっとも簡単なパスワード認証の一つです。ほぼ全てのブラウザに対応しており、認証用画面を作成することなくパスワード認証を行うことができます。nginxでは、デフォルトで組み込まれているngx_http_auth_basic_moduleを使用してBasic認証を利用できます。

Appacheに付属しているhtpasswdコマンドを使ってパスワードファイルを生成します。

~
sudo apt install apache2-utils

sudo htpasswd -c /etc/nginx/.htpasswd username #任意のユーザ名を記入
New password:  #任意のパスワードを入力
Re-type new password:
Adding password for user username

nginxの設定ファイルに以下を付け加えます。
auth_basic:basic認証の認証領域名を指定し、basic認証を有効にする
auth_basic_user_file:basic認証のユーザ名とパスワードを記述したファイルを指定します。

/etc/nginx/nginx.conf
http {
 #Basic認証
    auth_basic "basic-test";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

nginxを再起動して、設定ファイルを読み込ませます。

~
$ sudo systemctl restart nginx.service

IP制限

サーバー単位でアクセスの制限を行う場合は、

/etc/nginx/conf.d/default.conf
server {
    allow ***.***.***.***; #アクセスを許可するIPアドレス
    deny all;
}

ディレクトリごとのアクセス制限は、

/etc/nginx/conf.d/default.conf
location /制限先ディレクトリ/ {
    allow ***.***.***.***; #アクセスを許可するIPアドレス
    deny all;
}

おまけ
nginxのバージョン情報が表示されないようにする。

/etc/nginx/nginx.conf
http {
 # version off
    server_tokens off;
}

設定ファイルの書き込みが終わったら、nginxを再起動します。

~
$ sudo systemctl restart nginx.service
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2