How to Block URLs in NGINX


how to block urls in nginx

Sometimes, you may need to block several URLs on your website, in case they contain sensitive information. Here’s how to block URLs in NGINX.

 

How to Block URLs in NGINX

Here are the steps to block URLs in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. It is generally located at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Block URLs

Let’s say you want to block a single URL (/admin/login.php), then add the following location block in your config file


location ~ ^/admin/login.php {
 deny all;
}

 

If you want to block everyone except a few known IPs, then add them using the allow directive


location ~ ^/admin/login.php {
 allow 127.0.0.1;
 allow 192.168.0.1;
 deny all;
}

 

If you want to block everyone except a range of IP addresses (54.34.44.0-54.34.44.255), use the CIDR notation to specify a range of IPs


location ~ ^/admin/login.php {
 allow 54.34.44.0/24;
 deny all;
}

 

If you want to restrict access to all php files in only a specific directory (e.g /admin/), modify your location block as shown


location ~ /admin/\.php$ {
 deny all;
}

 

If you want to restrict access to all files in only a specific directory (e.g /admin/), modify your location block as shown


location ~ /admin/\.*$ {
 deny all;
}

 

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!