ELB配下のnginxでリモートIPを使ってアクセス制限をしたい
TL;DR
- AWS ELB配下で動く nginx でIP制限をしたいが、ELBからのヘルスチェックは通したい
- ngx_http_geo_module でリモートIPを分別し、別途 $http_user_agent を確認しつつ制限する条件で 403 を返せば出来る
なぜそんなことを?
AWS Lightsail でコンテナを動かしつつIP制限をしたかったのですが、単に ngx_http_access_module の alllow/deny で処理すると ELB からのヘルスチェックも 403 になってしまいます。
リモートIPアドレスをどう分別する?
リモートIPアドレスをCIDRで表現しつつ分別したいのですが、これは ngx_http_geo_module で出来ます。
set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;
geo $remote_addr $is_allowed {
default 0;
1.1.1.0/24 1;
2.2.2.0/24 1;
}
まとめるとこう
リバースプロキシのコンフィグとして書くと ( /etc/nginx/http.d/default.conf )
set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;geo $remote_addr $is_allowed {
default 0;
1.1.1.0/24 1;
2.2.2.0/24 1;
}server {
listen 80 default_server;location / {
if ($http_user_agent ~* "^ELB-HealthChecker/") {
set $is_allowed 1;
}
if ($is_allowed = 0) {
return 403 "Access Denied: $remote_addr\n";
}proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}