-1

In nginx, how can I restrict access to a certain URL prefix by IP address. i.e. “only these IPs are allowed to access $URL?”.

I have a location … { directive, but it looks like the nginx allow & deny do no work inside locations

I want all IP addresses to be able to access all parts of the server, but I want only a set few IP addresses to be able to access this URL prefix

nginx v 1.18.0 installed via apt on Uuntu Linux 22.04

2
  • 1
    Of course they do work in locations. Context: http, server, location, limit_except.
    – Alexey Ten
    Nov 23 at 16:09
  • Please share your full configuration as shown by nginx -T and clear details about "allow & deny do not work inside locations". Nov 23 at 18:55

1 Answer 1

2

To restrict access to a specific URL prefix in Nginx based on IP addresses, you can use the allow and deny directives inside a location block. The allow directive specifies which IPs are allowed, and the deny directive blocks all others. Here's how you can configure it:

  • Define a location block that matches your URL prefix.
  • Inside this block, use allow for each IP address you want to grant access.
  • Use deny all to block all other IP addresses.

Here's an example config for Nginx:

server {
    # ... other server config ...

    location /your_url_prefix/ {
        allow 192.168.1.100;   # Allow this IP
        allow 192.168.1.101;   # Allow another IP
        deny all;              # Deny all other IPs

        # ... other location config ...
    }
}

In this example, replace /your_url_prefix/ with your specific URL prefix and 192.168.1.100, 192.168.1.101 with the IP addresses you want to allow. After updating the configuration, make sure to reload Nginx to apply the changes.

  • Summary: Configure Nginx to restrict access to a specific URL prefix by IP using allow and deny directives within a location block.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .