How to Whitelist IP in NGINX


whitelist ip in nginx

If your website contains sensitive or confidential information, then its a good idea to allow only known IPs to access it. You can do this by whitelisting IPs on your web server. Otherwise, your website might attract malicious attackers. Let us take a look at how to whitelist IP in NGINX.

 

How to Whitelist IP in NGINX

Here are the steps to whitelist IP 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

You can whitelist IPs using Allow directive, followed by an IP or IP range. If you want to whitelist only a couple of IPs (54.45.43.23 and 96.143.111.10) to your entire site then add the following code to location block of your config file.


location / {
Allow 54.45.43.23;
Allow 96.143.111.10;
Deny All;
}

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


location /admin {
Allow 54.45.43.23;
Allow 96.143.111.10;
Deny All;
}

 

OR


location ^~ /admin {
Allow 54.45.43.23;
Allow 96.143.111.10;
Deny All;
}

 

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


location /login.php {
Allow 54.45.43.23;
Allow 96.143.111.10;
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.45.43.23;
Allow 96.143.111.10;
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!