NGINX Restrict Access to URL

Sometimes you may need to limit access to URL on your website. In this article, we will look at how to restrict access to URL in NGINX.


How to Restrict Access to URL in NGINX

Here are the steps to restrict access to URL in NGINX.


1. Open NGINX configuration file

Open terminal and run the following command to open NGINX configuration file.

$ sudo vi /etc/nginx/nginx.conf

If you have configured separate virtual hosts for your website (e.g www.example.com), such as /etc/nginx/sites-enabled/example.conf then open its configuration with the following command

$ sudo vi /etc/nginx/sites-enabled/example.conf

Also read : How to Configure NGINX Log Rotation


2. Restrict Access to URL

Let us say you want to limit access to /product.html URL by IP 45.34.21.10.

In that case add the Deny directive

Deny 45.34.21.10

in the location block for /product.html, in your NGINX server configuration.

location /product.html {
   ...
   deny 45.34.21.10;
   ...
}

If you want to restrict access to URL by all IPs except one known IP 45.34.21.10, then add the following Deny and Allow statements as shown.

location /product.html {
   ...
   Allow 45.34.21.10;
   Deny All;
   ...
}

The allow statement will allow access to specified IP and deny statement will limit access to all other IPs.

Also read : How to Fix NGINX Worker Connections Not Enough

If you want to limit access to URL for multiple IPs add separate Deny statements, one for each IP as shown.

location /product.html {
   ...
   Deny 45.34.21.10;
   Deny 54.23.10.13;
   ...
}

If you want to limit access to URL for an IP range such as 45.23.10.0-45.23.10.255 then specify IP range using CIDR notation.

location /product.html {
   ...
   Deny 45.34.21.0/24;
   ...
}

Also Read : How to Disable ETag in NGINX


3. Restart NGINX Server

Finally, run the following command to check syntax of your updated config file.

$ sudo nginx -t

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it today!

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform for small & medium businesses. Build dashboards, charts & reports for your business in minutes. Get insights from data quickly. Try it for free today!