nginx to white-list ip or ask for password

Let, you want to protect a page or any site in nginx by certain IP addresses access only. How would you do it in nginx? I will discuss some cases here about the situation.

You can give access to certain IP’s only by using:

allow 192.168.100.10;
allow 192.168.200.20;
deny all;

But somehow you need to give access outside world too for collaborations and their IP is not static or fixed. So, you can not allow all IP’s, what would you do?

You can use “satisfy any” tag to do something as: First check if the user is from white-list ip, If yes then obviously he/she can access it. But the ip is not in white-list then it will ask user:password to access the site. You can do this by:

satisfy any;
 allow 192.168.100.10;
 allow 192.168.200.20;
 deny all;
 # Auth
 auth_basic "Restricted Content ! You need password to access this site.";
 auth_basic_user_file /etc/nginx/basicauth/default;

By the way, If you use nginx in front of tomcat loading spring security application then password will be asked repetitively which is frustrating. You need to pass blank authorization header.

proxy_set_header Authorization "";

As an example:

 location / {
   proxy_set_header X-Forwarded-Host $host; 
   proxy_set_header X-Forwarded-Server $host; 
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
   proxy_pass http://127.0.0.1:8080/; 
   proxy_intercept_errors on; 
   proxy_redirect off;
   proxy_set_header Authorization "";
}

That is it. Thank you.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.