LoginSignup
3
5

More than 5 years have passed since last update.

CDN利用時の実IP取得、国別フィルタは、Nginxで処理する

Posted at

IPフィルタ

CDN利用時に、実IPのかわりにCDNのIPが来る場合。
(AWSの一部のサービスでも同じ方法で。)

・iptablesで見えるのは、CDNのIPなので注意。
・処理対象がHTTPヘッダなので、iptablesではなく、Nginxなどで処理する。
・CDNが付けてくれる、X-Forwarded-Forなどを利用する。

Nginx
Module ngx_http_realip_module が必要。
ビルド時のconfigに、--with-http_realip_module をつける。

set_real_ip_from、real_ip_headerは、

Context: http, server, location

なので、http、server、locationなどで処理する。

set_real_ip_from CDNのネットワークアドレス;
real_ip_header X-Forwarded-For;

または、

set_real_ip_from CDNのネットワークアドレス;
real_ip_header CF-Connecting-IP;

※CF-Connecting-IPは、CDNがCloudFlareの場合に利用可能。

参考:
How do I restore original visitor IP with Nginx?
CloudFlare IP Ranges


国別フィルタ

・iptablesで見えるのは、CDNのIPなので注意。
・処理対象がHTTPヘッダなので、iptablesではなく、Nginxなどで処理する。
・CDNが付けてくれる、CF-IPCOUNTRYなどを利用する。
 (または、set_real_ip_fromで実IPに戻したあとに処理する。・・おそらく重い。)

if文での分岐を増やさないために、mapを使って、CF-IPCOUNTRYで渡された情報を、yes または noに振り分けます。
(allow、yes、noは、別の名前でも可)
例:JPだけをyesにする場合。
httpブロックで

map $http_cf_ipcountry $allow {
    default no;
    JP yes;
}

serverブロックまたはlocationブロックで

if ($allow = no) {
    return 403;
}

※returnが表示するのは、Nginxのデフォルトのエラーページです。
 (error_pageで指定したページではありません。)
returnは、300番台(301, 302, 303, 307)以外は、別のアドレスに転送できません。
※転送できないエラータイプの場合は、

return code [text];

として解釈されるので、転送先だと思って書いたアドレスが、そのままテキストとして表示されます。要注意。

参考:
Using CloudFlare for country blocking

3
5
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
3
5