I have one question. Is it possible to block access to all files in folder if folder contains specific file e.g. .block. I know I can count on:

location ~ \.(mp3|log|txt|rtf|doc|docx)$ {
    deny all;
    return 404;

If it's possible, how to do this?

I have try with:

location ~ \.block {
    deny all;
    return 404;

But this function restrict only .block file, not files inside folder (still available to download or plain open in browser)


  • How are the .block files created? Automatically or manually by you? If the later, I suggest restricting the access to fodlers manually in NginX config as well. If automatically by a webapplication for example. then (geezus, forgive me to say this), maybe an if statement can help you, but do not forget: IFISEVIL – Bert Mar 19 '18 at 8:38
  • Yup, the .block files are created by myself. I don't want to write every folder name in NginX config, it's pointless. I just want to deny access to all files inside folder with .block file. Humm, like apache .htaccess deny from all. – user461339 Mar 19 '18 at 8:53

I'm affraid what you are trying to achieve is not present in NginX by default. You could use an IF statement, but you know.... IFISEVIL

Since you add these files manually, you can just go with this:

location ~ /(folder1|folder2|folder3|...) {
        deny  all;

This way, you won't need to create new location each time you want to block a folder. Just add the folder to the list in this one and you are ready to go.

| improve this answer | |
  • Bad... As I thought, it's impossible to do with my way. Thanks for answers! – user461339 Mar 19 '18 at 9:02

When directory names are unknown or changing permanently - it is possible using the @Bert answer to generate separate config with collected names via bash-script and execute it by cron.

1. The script for finding directories and collect them in nginx config.

#! /bin/bash

# Search directories with file '.block' and collect them in a variable. 
# Format dir1|dir2|dir3   
DIR_NAMES=$(find ~/temp -type f -name '.block' -printf '|%h')

# remove first "|"

# generate new config with names
echo "location ~ /($DIR_NAMES) {
  deny  all;
}" > nginx-block-directories.conf

# reload nginx with a new config
sudo nginx reload

2. Include generated config into main nginx config, for example in "server" section:

include nginx-block-directories.conf;

3. Refresh nginx config every night (crontab -e):

30 3 * * * /path/script.sh
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.