How can I protect all files and other directorys in a specific directory (-> recursively) in Nginx so they can't be accessed from the web?
Asked
Active
Viewed 1,218 times
1 Answers
4
You can deny access to locations with a specific prefix. nginx
resolves locations to directory paths by using the value of the root
or alias
directive.
The prefix location
with the ^~
modifier takes highest precedence and can therefore be used to deny access to specific parts of the hierarchy:
location ^~ /secret { deny all; }
location ^~ /secret { return 404; }
The above will return a 403 or 404 error response to any URI beginning with /secret
.
See this document for details.

Richard Smith
- 12,834
- 2
- 21
- 29
-
1Just out of curiosity, why the ^~ specifier? – Florin Asăvoaie Jan 10 '16 at 11:14
-
1@FlorinAsăvoaie It forces the precedence to be above a regex location. Otherwise `/secret/path.php` would not be protected by the above rules. – Richard Smith Jan 10 '16 at 11:17
-
That is false unless you have some other rules with a longer match on /secret/path.php – Florin Asăvoaie Jan 11 '16 at 13:20
-
@FlorinAsăvoaie `/secret/path.php` matches `location ~ \.php$` and `location /secret`. The first takes precedence because *any* matching regex location takes precedence over a prefix location (unless the `^~` modifier is specified for the latter). – Richard Smith Jan 11 '16 at 13:36
-
I get that but there was no mention of the php thingie location in the question. – Florin Asăvoaie Jan 12 '16 at 08:07
-
@FlorinAsăvoaie Understood. My answer to your original question was ambiguous. I used the example for illustrative purposes only. – Richard Smith Jan 12 '16 at 08:13