How to Whitelist Localhost in NGINX


whitelist localhost in nginx

When your website is under development or maintenance, you might need to block access to all but localhost. So let us take a look at how to whitelist localhost in NGINX.

 

How to Whitelist Localhost in NGINX

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

Let’s say all pages on your website/portal are password protected/restricted and you want to allow access to only to localhost. In that case, update your location block as shown,


location / {
Allow 127.0.0.1;
Allow 192.168.0.0/24;
Deny All;
}

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


location /admin {
Allow 127.0.0.1;
Allow 192.168.0.0/24;
Deny All;
}

 

OR


location ^~ /admin {
Allow 127.0.0.1;
Allow 192.168.0.0/24;
Deny All;
}

 

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


location /login.php {
Allow 127.0.0.1;
Allow 192.168.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 127.0.0.1;
Allow 192.168.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!