2

What I have:

# nginx.conf
http {
    map "$request_uri" $abort {
        default 0;
        "~*example" 1;
    }
    include sites-enabled/*.conf;
    # etc
}
# sites-enabled/example.com.conf
server {
    listen 80;
    location ~ \.js {
        if ($abort = 1) {
            return 500;
        }
    }
    # etc
}
# sites-enabled/example.net.conf
# sites-enabled/example.org.conf
# etc.

What is the problem:

  • I used map because if is evil. Now, $abort has a flag, knowing whether to proceed or not.
  • I don't know how to utilise that variable other than in an if statement. These comments confirm.
  • An if is allowed only no deeper than the server{} context. I have 12 sites, 3 server{}s each.

What I want:

Evaluate $abort and tell Nginx to return 500 somewhere on the shared http {} level.

Avoid repeating the if for every server {} of every virtual host.

I know I can put the if into e.g. snippets/abort.conf and include it, but that seems like cluttering and waste of resources. I hope there is a more elegant way. Do you know any?

4
  • Just to clarify: the if itself is not a problem, having to repeat it is. – aexl Oct 9 '19 at 13:54
  • Nope. Just use include or may be some sort of templating to generate your server blocks (if applicable) – Alexey Ten Oct 9 '19 at 13:57
  • 1
    If you look at your linked document, if in a location context is only 100% safe with return and rewrite...last. Your conditional abort statement uses a return and is therefore 100% safe. – Richard Smith Oct 9 '19 at 14:18
  • @RichardSmith thank you for your input, like I said my problem is cluttering and having to repeat the config across all servers; I'm looking for a way to tell Nginx to stop once and for all sites, no matter how many there are. The without using if? part in the title may have been confusing. It refers to if needing to be no deeper than server context. – aexl Oct 10 '19 at 6:17

Your Answer

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

Browse other questions tagged or ask your own question.