Nginx allow only root and api locations

Deena picture Deena · Feb 9, 2018 · Viewed 8.4k times · Source

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

so the server should only allow requests to the given paths

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

The expected behaviour is that the server should reject all the below possibilities.

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

my current nginx configuration,

server {

   # server configurations

   location / {

        # reverse proxy configurations

    }

}

How do I set up this configuration?

Answer

ffeast picture ffeast · Feb 11, 2018

Here it is:

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

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

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

From the docs:

Using the “=” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a “/” request happens frequently, defining “location = /” will speed up the processing of these requests, as search terminates right after the first comparison.