How to Whitelist IP Range in NGINX


whitelist ip range in nginx

If your website has sensitive information, then it might be a good idea to whitelist IP ranges who are allowed to access your site. Otherwise it might become vulnerable to malicious attacks. Here’s how to whitelist IP range in NGINX.

 

How to Whitelist IP Range in NGINX

Here are the steps to whitelist IP range in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will typically find it at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Whitelist IP ranges

You can whitelist IPs using Allow directive, followed by an IP or IP range. If you want to whitelist a couple of trusted IP ranges (54.0.0.0-54.255.255.255 and 96.0.0.0-96.255.255.255) to your entire site then add the following code to location block of your config file.


location / {
Allow 54.0.0.0/24;
Allow 96.0.0.0/24;
Deny All;
}

If you want to restrict access to a specific folder (e.g /admin)


location /admin {
Allow 54.0.0.0/24;
Allow 96.0.0.0/24;
Deny All;
}

 

OR


location ^~ /admin {
Allow 54.0.0.0/24;
Allow 96.0.0.0/24;
Deny All;
}

 

If you want to restrict access to a specific URL (e.g /login.php),


location /login.php {
Allow 54.0.0.0/24;
Allow 96.0.0.0/24;
Deny All;
}

 

You can also put the above Allow and Deny statements in a separate file /etc/nginx/shared-configs/whitelist.conf
and include it in your server block. For example,

 

#whitelist.conf


Allow 54.0.0.0/24;
Allow 96.0.0.0/24;
Deny All;

 

#nginx.conf


server {
 server example.com;
 include /etc/nginx/shared-configs/whitelist.conf;
}

 

3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!