Search code examples
nginxwebserverweb-hostingaccess-controlnginx-location

Nginx allow only root and api locations


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?


Solution

  • 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.