Nginx - resolving the source IP address

Nginx supports allow and deny syntax for restricting IP addresses, for example. allow 192.168.1.1; . But if traffic goes through a reverse proxy, the IP will refer to the proxy IP. So, how can it be configured to whitelist a specific IP source and block all other incoming requests?

+11
proxy nginx whitelist
source share
2 answers

remote_addr will refer to the proxy server, but you can configure the proxy server to send the client address with the X-Real-IP / X-Forwarded-For header fields.

In combination with the ngx_http_realip module, you can change the incoming header to use the real client address for remote_addr. I believe this will work as expected with allow / deny syntax.

Just to clarify - the allow / deny syntax should be identical after you enable and configure the module. Substitute your IP address and your proxy addresses below.

Back-end nginx enable / disable:

 location / { allow <your ip>; allow 127.0.0.1; deny all; } 

Nginx realip back-end configuration:

 set_real_ip_from <your proxy>; real_ip_header X-Forwarded-For; 

In your nginx proxy configuration:

 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

If you have several intermediate proxies, you need to enable the additional addresses real_ip_recursive and whitelist using the set_real_ip_from directive.

+12
source share

I worked with the following configuration using the http_geo module:

 geo $remote_addr $give_access { proxy 172.0.0.0/8; # <-- Private IP range here default 0; 11.22.33.44 1; # <-- Allowed IP here } server { # more config ... location ^~ /secure_url_here { if ($give_access = 0) { return 403; } try_files $uri $uri/ /index.php?$args; # <-- Your directive here } } 

Ref: http://nginx.org/en/docs/http/ngx_http_geo_module.html

+1
source share

All Articles