Nginx only allows root and api locations

I have a server configured as a reverse proxy for my server. I want to reject all requests except two places, one for the root and the other the api root.

therefore, the server should only allow requests to the specified paths

example.com/ (only the root)
example.com/api/ (every url after the api root)

The expected behavior is that the server should reject all of the following features.

example.com/location
example.com/location/sublocation
example.com/dynamic-location

my current nginx configuration,

server {

   # server configurations

   location / {

        # reverse proxy configurations

    }

}

How to configure this configuration?

+4
source share
2 answers

There he is:

   location = / {
        # would serve only the root
        # ...
    }

    location /api/ {
        # would serve everything after the /api/
        # ...
    }

You need a special modifier '=' to make the root location work as expected

From docs :

"=", URI . , . , "/", "location =/", , .

+4

if, , $request_uri, root, /api/, location server:

if ($request_uri !~ ^/$|^/api/) {return 403;}

, , - , nginx 3 location, - /, /api/, , http://nginx.org/r/location.

, , , $is_args ( $args/$query_string, ), , , URL- / - ( , location $request_uri, $uri, ).

location = / {
    # handle root
    if ($request_uri != "/") {
        # ensure $query_string and $is_args are not allowed
        return 403 "<h1>403: query_string not allowed</h1>\n";
    }
}
location /api/ {
    # handle the /api/ prefix
}

location / {
    # handle everything else
    return 403;
}
+3

Source: https://habr.com/ru/post/1693406/


All Articles