towel
towel

Reputation: 2214

Restrict access to a certain URL prefix

I want to block access to all URLs in my server except URLs starting with /myapp/path, excluding /myapp/path/nope, which should be blocked as well.

I tried:

nginx.org/server-snippets: |
  location = /myapp/path/nope { return 404; }
  location ^~ /myapp/path {}
  location / { return 404; }

But got 404 messages on URLs starting with /myapp/path as well. To be frank, even after reading the documentation and trying all sorts of things it seems I haven't figured out how nginx determines what location to serve. What it wrong with my snippet? Thanks!

Upvotes: 0

Views: 1116

Answers (1)

towel
towel

Reputation: 2214

Eventually I resolved this issue using a negative regex. In my question I used the location and the regex incorrectly, as I never told nginx what to do with the path I wrote.

So in order to restrict access to anything that doesn't start with /myapp/path use:

location ~ ^/(?!myapp/path) { return 404; } # Or deny all;

Upvotes: 1

Related Questions