1

My website is running behind aws Load Balancer. Now if i try to deny any IP to access my website by using "deny 59.92.130.106" under location / nothing happened. That IP still getting 200 response.Anyone having idea why this happened and how can i block any ip in nginx running behind aws load balancer? I used below entry but it is not working.

location / {
    deny 59.92.130.106;
}
Rocky
  • 49
  • 2
  • 9

2 Answers2

1

Thanks all for help. I found solution for this issue. Maybe there is some bug in nginx due to which i found double IP in $http_x_forwarded_for but with the help of real_ip module now i able to block IP using $remote_addr header. By including below code in my vhost conf now i get client IP in $remote_addr header.

set_real_ip_from 0.0.0.0/0;
        real_ip_header X-Forwarded-For;
        real_ip_recursive on;

set $allow true;
if ($remote_addr ~ "180.179.") {
     set $allow false;
}
if ($remote_addr ~ "199.47.") {
     set $allow false;
}
if ($allow = false) {
     return 403;
}
Rocky
  • 49
  • 2
  • 9
0

If your load balancer is properly configured to support X-Forwarder-For HTTP header, you can use something like

map $http_x_forwarded_for $block {
    59.92.130.106         1;
    <another_blocked_ip>  1;
    ...
}
server {
    ...
    location / {
        if ($block) { return 403; }
        ...
    }
    ...
}

or if you want to allow access forsome IPs only

map $http_x_forwarded_for $block {
    59.92.130.106         '';
    <another_allowed_ip>  '';
    ...
    default               1;
}
Ivan Shatsky
  • 2,726
  • 2
  • 7
  • 19
  • I tried `map $http_x_forwarded_for $block { 59.74.236.125 1; }` and `location / { if ($block) { return 403; } try_files $uri $uri/ /index.php?$args; }` But still it's not working – Rocky Jul 08 '20 at 09:57
  • @RahulAggarwal The AWS documentation [says](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html) their load balancers should support `X-Forwarded-For` header. You can try to debug this defining [custom log format](http://nginx.org/ru/docs/http/ngx_http_log_module.html#log_format) for your access log with `$http_x_forwarded_for` field included and check if this header is really set by load balancer. If it isn't, check your load balancer configuration. Didn't know how to help further. – Ivan Shatsky Jul 08 '20 at 10:31
  • I already configured custom log format with "$http_x_forwarded_for" and getting client IP but didn't know how to use `$http_x_forwarded_for` for blocking that same IP. – Rocky Aug 06 '20 at 06:13
  • @RahulAggarwal Try `if ($block) { return 403; }` outside of the `location` block if you have several locations defined. – Ivan Shatsky Aug 06 '20 at 09:29
  • I also tried if ($block) { return 403; } outside of the location block but still it's not working – Rocky Oct 03 '20 at 07:53
  • @RahulAggarwal Sorry, I don't know what to suggest further. – Ivan Shatsky Oct 03 '20 at 07:56