0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

nginxで特定のIPからのアクセスを禁止する方法

Posted at

nginxで特定のIPアドレスからのアクセスを禁止するには、nginxの設定ファイルに以下のような設定を追加します。この設定は通常、nginxのメイン設定ファイル(nginx.conf)やサイトごとの設定ファイルに追加します。

手順

  1. 設定ファイルを開く
    nginx.conf または対象のサーバブロックがある設定ファイルを編集します。
    通常は、次のように設定ファイルを編集します。
    sudo nano /etc/nginx/nginx.conf
    
  2. 設定を追加する
    serverブロックの中に、以下のように denyディレクティブを追加します。
    server {
      listen 80;
      server_name example.com;
      # 特定のIPアドレスからのアクセスを禁止
      deny 192.168.1.100; # 禁止したいIPアドレス
      deny 203.0.113.0/24; # サブネット全体を禁止する場合
      # 許可するIPアドレスがある場合はallowを使用
      allow 192.168.1.0/24;
      # 他のIPアドレスからのアクセスを許可
      allow all;
      location / {
        # 通常の設定
        proxy_pass http://localhost:3000;
      }
    }
    
    
    

    設定をテストする
    設定ファイルにエラーがないか確認するため、以下のコマンドを実行します。
    sudo nginx -t
    
  3. nginxを再起動する
    設定ファイルが正しい場合、nginxを再起動して設定を反映させます。
    sudo systemctl restart nginx
    

補足

  • denyディレクティブに指定されたIPアドレスは、403 Forbiddenエラーが返されます。
  • 特定のIPだけを許可する場合は、allowディレクティブを使用し、許可したいIP以外のアクセスを禁止するように設定することもできます。

この設定により、指定したIPアドレスやサブネットからのアクセスを制限することができます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?