I have a directory that sometimes exists and sometimes does not. If requested and existent, all files in it should be made available, e.g. like this
location /my_dir {
root /other/www/root
}
Thus if a user asks for http://myhost.example.com/my_dir/file
and /my_dir
exists, it should be served. However, if the directory /other/www/root/my_dir
does not exist, nginx should act as if the location block was never defined and use the normal rules to handle the request. Specifically, the client should not be aware of this special rule if the directory currently does not exist, i.e. there should be no user-visible indicator for it.
One idea was to put the default configuration in a named location and change the above lines to the following (cf. How to write a DRY, modular nginx conf (reverse proxy) with named locations):
location /my_dir {
root /other/www/root
try_files $uri $uri/ @default;
}
location / {
error_page 418 = @default;
return 418;
}
location @default {
# all default stuff like the default root, index etc. goes here
}
Does that make sense or is there a better way?
Update
Here are two example configurations for nginx:
# Example 1
server {
listen 80;
listen [::]:80;
server_name www.example.com example.com
root /var/www/www.example.com
index index.html index.htm
}
# Example 2
server {
listen 80;
listen [::]:80;
server_name www.example.com example.com
return 301 https://$server_name/$request_uri
}
In each case, I would like to add the special rules for the /my_dir
location but only if the special root directory /other/www/root
currently exists. If it doesn't, the client should not notice the special treatment for the /my_dir
location.