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?

More than 1 year has passed since last update.

【備忘録】nginxでローカル環境からのアクセスログを除外する

Posted at

はじめに

nginxでアクセスログを収集する際、ローカル環境から接続した際のアクセスログが混じって鬱陶しかったので、アクセスログから除外する設定をしたので、その備忘録を書き残して置きます。

geoディレクティブを使う

クライアントのIPアドレスを変数($記号がついてるやつ)に入れることができます。

ipアドレスを範囲で指定したいときは、最初にrangesという記述をします。
下の例では、$is_globalに0か1が入ります。

  • プライベートIPアドレス→0
  • グローバルIPアドレス→1

厳密な話をすると、10.0.0.0 ~ 10.255.255.255もクラスAのプライベートIPアドレスです。ただ、大規模なネットワーク環境で使われるもので、私が使うことはなさそうだったので書いてません。

geo $is_global { # グローバルIPアドレスか判定
    ranges;
    192.168.0.0-192.168.255.255 0;
    172.16.0.0-172.31.255.255 0;
    default 1;
}

access_log /var/log/nginx/myweb-access.log combined if=$is_public;

access_logのifで、is_publicが1のときのみアクセスログを記録するという指定をしています。ですので、結果としてプライベートIPアドレスからのアクセスは除外されるようになります。

botのアクセスを拒否

ついでに、この設定も書いておきます。アクセスログを一度眺めるとわかりますが、個人サイトを外部公開していると、botからのアクセスが大量にきます。こんなの個人が受け入れるメリットないので、全部拒否します。

map $http_user_agent $bot {
    ~*(SemrushBot|AhrefsBot|Linguee|proximic|BLEXBot|GrapeshotCrawler|Mappy|MJ12bot|MegaIndex|bidswitchbot|SMTBot|ltx71|integralads|jet-bot|trendictionbot|bingbot|Googlebot|DotBot) 1;
    default 0;
}

server {
    if ($bot) {
        return 444;
    }
    # 以下もろもろのサーバ設定
    ・・・
}

444はnginxに用意されている特別なステータスコードで、何も返さないという挙動になります。

\$http_user_agentはデフォルトで用意されている変数で、「Chrome」だとか「iPhone」みたいなアクセス元が入ります。$botは独自に用意した変数で、アクセス元がbotなら1、その他は0が入ります。

短いですがおわり。セキュリティ対策は必ずやりましょうね。

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?